Technical SEO

Next.js canonical tag: alternates.canonical, metadataBase, query strings and pagination

How Next.js builds the canonical URL, tested on Next.js 16: what './' resolves to, why a layout canonical leaks to every child page, query strings, pagination, trailing slashes, and canonicals that end up in the body.

By SEOFix TeamPublished Updated
1,726 words · 8 min readMarkdown
Next.js canonical tag: alternates.canonical, metadataBase, query strings and pagination

To add a canonical tag in the Next.js App Router, set metadataBase once in the root layout and return alternates: { canonical: '/path' } from each page's metadata or generateMetadata. Next.js turns the path into an absolute URL and renders <link rel="canonical" href="https://example.com/path">. Build the path from the route, not from the request, so query strings such as ?utm_source= never reach the canonical. The exceptions are paginated pages, which keep their ?page=n.

That covers the happy path. The rest of this guide is about the places where Next.js does something you might not expect. We checked each one against a Next.js 16.4.2 production build on 2 November 2026; the outputs below are copied from curl.

The basic setup

// app/layout.tsx
import type { Metadata } from 'next'

export const metadata: Metadata = {
  metadataBase: new URL('https://example.com'),
  title: { default: 'Example', template: '%s · Example' },
}
// app/blog/[slug]/page.tsx
import type { Metadata } from 'next'
import { getPost } from '@/lib/posts'

type Props = { params: Promise<{ slug: string }> }

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { slug } = await params
  const post = await getPost(slug)
  return {
    title: post.title,
    alternates: { canonical: `/blog/${post.slug}` },
  }
}

The output for /blog/hello-world:

<link rel="canonical" href="https://example.com/blog/hello-world"/>

Note post.slug rather than the slug from the URL. If your lookup is case-insensitive or accepts old slugs, /blog/Hello-World would otherwise canonicalise to itself.

Google wants exactly this: an absolute URL, in the <head>, on every version of the page. Its canonicalization guide says to "use absolute paths rather than relative paths", and that the element "is only accepted if it appears in the <head> section of the HTML."

How metadataBase builds the URL

From the generateMetadata reference:

  • A relative path in a URL field "will be composed with metadataBase to form a fully qualified URL."
  • "If a metadata field provides an absolute URL, metadataBase will be ignored."
  • "Using a relative path in a URL-based metadata field without configuring a metadataBase will cause a build error."

That build error is a useful guard: you can't ship a relative canonical by accident. The bug you can ship is a metadataBase that points at the wrong host.

Don't build metadataBase from the request or the deployment URL

These all produce canonicals that point somewhere other than production:

// each of these is wrong for a canonical
metadataBase: new URL(`https://${process.env.VERCEL_URL}`)          // the per-deployment *.vercel.app host
metadataBase: new URL(process.env.NEXT_PUBLIC_SITE_URL ?? 'http://localhost:3000')
metadataBase: new URL(`https://${(await headers()).get('host')}`)   // whatever Host the client sent

VERCEL_URL is "the domain name of the generated deployment URL", per Vercel's docs. A preview deployment that canonicalises to itself is harmless on its own, but the same code in production canonicalises every page to my-app-abc123.vercel.app if the variable is read there. The Host header version lets any alias, staging domain or www variant become its own canonical.

Hard-code the production origin, or use a variable that is the same everywhere. On Vercel, VERCEL_PROJECT_PRODUCTION_URL is "always set, even in preview deployments":

// lib/site.ts
export const SITE_URL = process.env.VERCEL_PROJECT_PRODUCTION_URL
  ? `https://${process.env.VERCEL_PROJECT_PRODUCTION_URL}`
  : 'https://example.com'

Previews then canonicalise to production, which is what you want if a preview URL ever leaks.

The layout canonical that every page inherits

Metadata merges from the root layout down to the page, and a page that doesn't set a field inherits it from its parents (generateMetadata, Merging). We put alternates: { canonical: '/' } in app/inherit/layout.tsx, gave app/inherit/child/page.tsx no metadata at all, and got:

curl -s https://example.com/inherit/child | grep -o '<link rel="canonical"[^>]*>'
# <link rel="canonical" href="https://example.com"/>

The child page told Google it's a copy of the home page. This usually starts as a canonical added to the root layout "for the home page" and goes unnoticed because every page you test by hand sets its own. Our canonical tag mistakes post covers why Google then either ignores the tag or drops the page.

What './' resolves to

Next.js has a special case for paths that start with ./: it resolves them against the current pathname. You can see it in resolve-url.ts, where a ./ URL is passed through path.posix.resolve(pathname, url) before metadataBase is applied. In our test:

WhereValueRequestOutput
page.tsx'./'/canon/dothttps://example.com/canon/dot
page.tsx'rel'/canon/relhttps://example.com/rel
parent layout.tsx'./'/inh2/childhttps://example.com/inh2/child

So alternates: { canonical: './' } in the root layout gives every page a self-referencing canonical without query parameters, and a plain relative path like 'rel' is resolved from the root, not from the current folder. The URL composition table in the Next.js docs shows ./ resolving to the bare metadataBase, which is not what the installed version did for us, so treat this as observed behaviour and check it in your own build.

A root-layout './' is a reasonable safety net, with two catches:

  • It drops ?page=2 on paginated pages, which Google says not to do (see below). Paginated routes must set their own canonical.
  • It resolves against the requested path, not the record. A case variant or an old slug that still renders a 200 gets a canonical pointing at itself. Redirect those variants (see Next.js redirects) or set the canonical from the record.

Setting alternates in a page replaces the parent's

The merge is shallow: "Duplicate keys are replaced". If the layout sets alternates.languages for hreflang and the page sets alternates.canonical, the page's alternates object replaces the layout's entirely and the hreflang links disappear. Spread the parent value when you need both, as the SEOFix blog does for its markdown alternate:

const base = pageMetadata({ title, description, path })
return {
  ...base,
  alternates: { ...base.alternates, types: { 'text/markdown': `${path}.md` } },
}

Query strings

Because the canonical is built from the route, request parameters don't leak into it:

curl -s 'https://example.com/canon/ok?utm_source=x' | grep -o '<link rel="canonical"[^>]*>'
# <link rel="canonical" href="https://example.com/canon/ok"/>

That is right for tracking parameters, sort orders and view toggles. For filter pages it depends on what the filter does:

  • Filters that barely change the list (?sort=price, ?view=grid): canonical to the unfiltered URL.
  • Filters that create a page worth ranking (a category in a given city, say): give it a clean path such as /jobs/accountant/dubai with a self-referencing canonical, and link to it.
  • Internal search results (/search?q=…): don't rely on a canonical. Add robots: { index: false } in generateMetadata.

Google's guide warns against mixing methods: "don't specify one URL in a sitemap, but a different URL for that same page using rel="canonical"." Whatever your sitemap lists must be the URL the canonical points at. The Next.js sitemap post covers building that list.

Pagination

Google's pagination guide is direct: "Don't use the first page of a paginated sequence as the canonical page. Instead, give each page its own canonical URL." Pagination is the one case where a query parameter belongs in the canonical:

// app/blog/page.tsx
import type { Metadata } from 'next'

type Props = { searchParams: Promise<{ page?: string }> }

export async function generateMetadata({ searchParams }: Props): Promise<Metadata> {
  const n = Number((await searchParams).page ?? '1')
  const page = Number.isInteger(n) && n > 1 ? n : 1
  return {
    title: page > 1 ? `Blog, page ${page}` : 'Blog',
    alternates: { canonical: page > 1 ? `/blog?page=${page}` : '/blog' },
  }
}

Our test of /q?page=2&sort=price with this pattern produced https://example.com/q?page=2: the page number survives, the sort is dropped. Two details in that code matter. page=1 canonicalises to /blog, so the first page has one URL. And junk values (?page=abc, ?page=-1) fall back to page 1 instead of producing a canonical with garbage in it. Past the last page, call notFound().

Next.js also has a pagination field that renders <link rel="prev"> and <link rel="next">. Google says it "no longer uses these tags." They're harmless, but they don't replace the canonical or ordinary <a href> links between pages.

Trailing slashes

By default, Next.js "will redirect URLs with trailing slashes to their counterpart without a trailing slash" (trailingSlash docs). A canonical with a trailing slash therefore points at a redirect:

curl -s https://example.com/canon/slash | grep -o '<link rel="canonical"[^>]*>'
# <link rel="canonical" href="https://example.com/canon/slash/"/>
curl -sI https://example.com/canon/slash/ | grep -i -E '^HTTP|^location'
# HTTP/1.1 308 Permanent Redirect
# location: /canon/slash

Next.js didn't fix it for us: it outputs whatever path you give it. The opposite case is handled. With trailingSlash: true, the same resolve-url.ts appends a slash to canonicals on the metadataBase origin that have no query string and don't look like a file. So the safe habit is to write canonical paths without a trailing slash and let the config decide.

When the canonical ends up in the body

Since Next.js 15.2, generateMetadata can stream. The docs say that "when generateMetadata resolves, the resulting metadata tags are appended to the <body> tag", and that Next.js has "verified that metadata is interpreted correctly by bots that execute JavaScript and inspect the full DOM (e.g. Googlebot)." For user agents on the htmlLimitedBots list, such as Bingbot, metadata still blocks and lands in <head>.

We checked where the canonical sits on a page whose generateMetadata takes 300 ms:

Page setupcurl / Googlebot UABingbot UA
loading.tsx in the route<body><head>
No loading.tsx, page doesn't await the same data<body><head>
No loading.tsx, page awaits the same data (React cache)<head><head>
Googlebot added to htmlLimitedBots<head><head>

We also loaded the first page in headless Chromium with a Googlebot user agent: after JavaScript ran, the canonical was still inside <body>.

Next.js's claim and Google's documentation ("only accepted if it appears in the <head>") point in different directions, and we can't see inside Google's pipeline to settle it. You don't have to. Either of these puts the canonical in the head for everyone:

  1. Let the page wait for the data the metadata needs. Fetch through a shared cache()-wrapped function in both generateMetadata and the page, with no loading.tsx above the route. This is also how you keep a real 404 status, covered in Next.js 404 status code.
  2. Block metadata for Googlebot. Setting htmlLimitedBots replaces the default list, so include the bots you still want:
// next.config.ts
import type { NextConfig } from 'next'

const config: NextConfig = {
  htmlLimitedBots:
    /Googlebot|bingbot|[\w-]+-Google|Google-[\w-]+|DuckDuckBot|Applebot|facebookexternalhit|Twitterbot|LinkedInBot|Slackbot/i,
}

export default config

The docs warn that overriding the list "could lead to longer response times". For Googlebot the cost is the time generateMetadata takes, on every crawled page.

Google's JavaScript SEO guide adds one more rule that applies here: if JavaScript sets the canonical, "make sure that this is the only rel="canonical" link tag on the page." A root-layout canonical plus a streamed page canonical gives you two.

Check every template

# canonical, and whether it sits before </head>
check() {
  curl -s -A 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)' "$1" \
  | python3 -c "
import re,sys
h=sys.stdin.read(); end=h.find('</head>')
tags=[(m.group(1), 'head' if m.start()<end else 'BODY') for m in re.finditer(r'<link rel=\"canonical\" href=\"([^\"]*)\"',h)]
print(sys.argv[1], tags or 'NO CANONICAL')" "$1"
}
check 'https://example.com/blog/hello-world?utm_source=test'
check 'https://example.com/blog?page=2'
check 'https://example.com/about'

# does the canonical answer 200 without redirecting?
curl -s -o /dev/null -w '%{http_code} %{redirect_url}\n' https://example.com/blog/hello-world

You want one canonical per page, in the head, absolute, on the production host, without tracking parameters, answering 200.

On a whole site, SEOFix runs these checks on every crawled page: CANONICAL_MISSING, CANONICAL_TO_REDIRECT (including trailing-slash mismatches), CANONICAL_TO_BROKEN, and CANONICAL_TO_OTHER_PAGE, which carries a to_homepage flag for the inherited-layout bug (indexability checks). Its JavaScript render sample also compares the canonical in the raw HTML with the one after rendering, which catches a client component that rewrites it (JavaScript rendering).

FAQ

Do I need a canonical on every page? Google doesn't require one, but any page reachable with parameters (tracking links, ads, sorting) has duplicates, and a self-referencing canonical tells Google which one you mean. In Next.js it costs one line per template.

Can the canonical point to another domain? Yes. An absolute URL ignores metadataBase. Use it for syndicated content, and make sure the other domain's page is a real copy.

Google ignored my Next.js canonical. Why? Usually the other signals disagree: internal links, the sitemap or redirects point at a different URL. Google chose different canonical walks through reading URL Inspection for this.

Does alternates.canonical work in a client component? No. metadata and generateMetadata are only supported in Server Components, per the generateMetadata reference.


Check the canonical on every template at once: the first SEOFix audit is free (up to 500 pages).

ShareXLinkedIn