New researchTechnical SEO & AI Search · 2027Explore the framework

Next.js SEO: a step-by-step setup guide for the App Router

Set up SEO in a Next.js App Router site: metadata, canonicals, sitemap.ts, robots.ts, hreflang, JSON-LD, real 404s, redirects and a pre-deploy check.

Part of the JavaScript SEO series. For the full picture, start with JavaScript SEO: the complete rendering and indexing guide.

Next.js gives search engines what they need most: pages rendered on the server. In the App Router, layouts and pages are Server Components by default, and the Server and Client Components guide says Client Components are prerendered to HTML too. The first response contains the content, without waiting for JavaScript.

What Next.js doesn’t do is decide which URL is canonical, which pages belong in the sitemap or what a missing page should return. Its metadata API makes those decisions easy to write, and also easy to get subtly wrong through inheritance and streaming. This guide sets them up step by step for the App Router, with code based on the Next.js 16.4 documentation. For the reasoning behind each rule on any framework, see the static site SEO checklist; the Astro SEO guide covers the same setup for Astro.

Step 1: What does Google get from a Next.js page?

The HTML your server sends, plus whatever Google renders later. Keep everything that matters for indexing in the first part.

  • Server Components fetch data and render on the server. Use them for page content.
  • Client Components ('use client') are prerendered to HTML on the first load and hydrated in the browser, so their initial output is in the HTML.
  • Data fetched in the browser (in useEffect, or with a client fetching library) is not in that HTML. The static exports guide shows this pattern for client-side data; it suits personalised or live widgets, not the main content.
  • Links: <Link> renders an <a> element with an href, per the Link reference, so crawlers can follow it. Don’t navigate with onClick handlers on non-link elements.

To see the difference on a real page, compare the response HTML with the rendered DOM, as in the raw vs rendered HTML audit.

Step 2: Set metadataBase and a title template in the root layout

The root layout sets what every page shares: the base URL, the title format and the language.

// lib/site.ts
export const SITE_URL = 'https://example.com'

/** Pages kept out of search. Page metadata and the sitemap both read this list. */
export const NOINDEX_PATHS = ['/thank-you', '/search']
// app/layout.tsx
import type { Metadata } from 'next'
import { SITE_URL } from '@/lib/site'

export const metadata: Metadata = {
  metadataBase: new URL(SITE_URL),
  title: { template: '%s | Example', default: 'Example' }
}

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>{children}</body>
    </html>
  )
}

From the generateMetadata reference:

  • metadataBase lets URL fields such as alternates.canonical and openGraph.images use relative paths. Using a relative path without it is a build error.
  • title.template applies to child segments only and requires title.default. A page that sets title: 'About' outputs <title>About | Example</title>.

What not to put here: a canonical. Metadata objects are merged shallowly, and a child segment that doesn’t set a field inherits it. If the root layout sets alternates: { canonical: '/' }, every page that forgets its own canonical declares the home page as its canonical URL. The same inheritance gives every page the layout’s og:title and og:description if the page doesn’t set openGraph. Leave both to the pages, and skip a default description too: a missing description is easier to catch than a duplicated one.

Step 3: Build every page’s metadata with one helper

Give pages one function that returns their whole SEO metadata. It decides canonical, robots, Open Graph and hreflang together, so they can’t contradict each other.

// lib/seo.ts
import type { Metadata } from 'next'
import { NOINDEX_PATHS } from './site'
import { alternatesFor } from './translations'

type PageSeo = {
  path: string
  title: string
  description: string
  image?: string
  type?: 'website' | 'article'
}

export function pageMetadata({ path, title, description, image = '/og/default.png', type = 'website' }: PageSeo): Metadata {
  const noindex = NOINDEX_PATHS.includes(path)
  const languages = noindex ? null : alternatesFor(path)

  return {
    title,
    description,
    // An explicit empty object replaces anything inherited, so a noindex page has no canonical.
    alternates: noindex
      ? {}
      : { canonical: path, ...(languages ? { languages: { ...languages, 'x-default': languages.en } } : {}) },
    robots: { index: !noindex, follow: true },
    openGraph: { type, title, description, images: [image], ...(noindex ? {} : { url: path }) },
    twitter: { card: 'summary_large_image', images: [image] }
  }
}

A static page uses it in its metadata export:

// app/about/page.tsx
import { pageMetadata } from '@/lib/seo'

export const metadata = pageMetadata({
  path: '/about',
  title: 'About',
  description: 'Who builds Example, why it exists and how to reach the team.'
})

Why this shape:

  • The canonical is the page’s own path. Google recommends a self-referencing canonical in its guide to consolidating duplicate URLs. Write paths in the same slash form as your trailingSlash setting (Step 8). The canonical errors guide covers what else breaks canonicals.
  • A noindex page gets robots: { index: false } and no canonical, og:url or hreflang. Saying “don’t index this” and “this is the URL to index” on one page is a contradiction.
  • x-default is a valid key. Next.js types alternates.languages with an hreflang union that includes x-default.
  • Every page sets its own openGraph, so nothing leaks from the layout through shallow merging.

Titles and descriptions should be distinct per page. Google’s title link documentation says titles are truncated to fit the device and warns against repeated or boilerplate titles.

Step 4: Keep metadata in the head when it matters

Check where your canonical ends up. The generateMetadata reference describes streaming metadata: when a page can’t be prerendered or generateMetadata is dynamic, Next.js may send the page first and append the metadata tags to <body> when they resolve. Next.js says it verified that bots which execute JavaScript, such as Googlebot, interpret this correctly; for HTML-limited bots it detects by user agent (such as facebookexternalhit), metadata blocks rendering and stays in <head>.

Google’s canonical documentation is strict about placement: rel="canonical" is only accepted in the <head>. If you’d rather not depend on how rendering moves the tags, you have two options:

  1. Make metadata static where you can. If the page can be prerendered and generateMetadata adds no dynamic behaviour, the reference says the metadata is included in the initial HTML.
  2. Disable streaming metadata with htmlLimitedBots: /.*/ in next.config. The reference warns this can lengthen response times, and calls streaming metadata an advanced feature whose default suits most cases.

Whichever you choose, check the raw HTML: the check in Step 11 fails when the canonical isn’t before </head>.

Step 5: Load content with one draft filter and real 404s

Write one function that returns publishable posts, and use it in pages, generateStaticParams, the sitemap and any feed:

// lib/posts.ts
import { getAllPosts } from './content' // your CMS client or MDX loader

/** Published posts, newest first. Drafts show only in `next dev`. */
export async function getPublishedPosts() {
  const posts = await getAllPosts()
  return posts
    .filter((post) => process.env.NODE_ENV === 'development' || !post.draft)
    .sort((a, b) => b.publishedAt.localeCompare(a.publishedAt))
}

export async function getPost(slug: string) {
  return (await getPublishedPosts()).find((post) => post.slug === slug)
}

The post route prerenders known slugs and returns a 404 for everything else:

// app/blog/[slug]/page.tsx
import { notFound } from 'next/navigation'
import { getPost, getPublishedPosts } from '@/lib/posts'
import { pageMetadata } from '@/lib/seo'

export const dynamicParams = false

export async function generateStaticParams() {
  return (await getPublishedPosts()).map((post) => ({ slug: post.slug }))
}

export async function generateMetadata({ params }: PageProps<'/blog/[slug]'>) {
  const { slug } = await params
  const post = await getPost(slug)
  if (!post) return {}
  return pageMetadata({
    path: `/blog/${slug}`,
    title: post.title,
    description: post.description,
    image: post.image,
    type: 'article'
  })
}

export default async function Page({ params }: PageProps<'/blog/[slug]'>) {
  const { slug } = await params
  const post = await getPost(slug)
  if (!post) notFound()

  return (
    <article>
      <h1>{post.title}</h1>
      {/* post body */}
    </article>
  )
}

The dynamicParams reference says that with false, segments not returned by generateStaticParams return a 404. It isn’t available when Cache Components is enabled; then the notFound() call is what protects you, which makes its timing important.

Why timing matters. The loading.js reference explains that streaming responses begin with a 200 status, and the status can’t change once the stream starts. If notFound() runs after that, for example in a page wrapped by a loading.js boundary, Next.js renders the not-found UI with status 200 and adds <meta name="robots" content="noindex">. The not-found.js reference says the same: 404 before streaming starts, 200 with noindex after. The docs note some crawlers may label those responses as soft 404s.

To keep a real 404:

  • Look the content up and call notFound() before any Suspense boundary suspends, at the top of the page.
  • Avoid a loading.js in segments where the 404 decision happens inside the page.
  • Or check the slug in Proxy and return a 404 there, as the loading.js reference suggests, keeping the check fast.

Unknown URLs that match no route are handled by app/not-found.js, which the reference says also serves unmatched URLs across the app. The soft 404 guide explains why the status code matters.

Step 6: Add JSON-LD in the page

Render structured data as a plain <script> tag in the page or layout, as the Next.js JSON-LD guide recommends. The guide warns that JSON.stringify doesn’t sanitise strings and suggests replacing < with <:

// components/json-ld.tsx
export function JsonLd({ data }: { data: object }) {
  return (
    <script
      type="application/ld+json"
      dangerouslySetInnerHTML={{ __html: JSON.stringify(data).replace(/</g, '\\u003c') }}
    />
  )
}

In the post page:

const url = new URL(`/blog/${slug}`, SITE_URL).href

<JsonLd
  data={{
    '@context': 'https://schema.org',
    '@type': 'BlogPosting',
    headline: post.title,
    description: post.description,
    datePublished: post.publishedAt,
    dateModified: post.updatedAt ?? post.publishedAt,
    author: { '@type': 'Person', name: post.author.name, url: new URL(post.author.path, SITE_URL).href },
    image: [new URL(post.image ?? '/og/default.png', SITE_URL).href],
    mainEntityOfPage: url
  }}
/>

Google’s Article structured data documentation has no required properties and recommends author, datePublished, dateModified, headline and image, with author.name holding only the name. Its structured data guidelines require markup to match visible content, so show the same dates and author on the page. The JSON-LD guide also mentions the schema-dts package if you want typed objects. Use next/script only for executable JavaScript; the guide says a native <script> is the right choice for JSON-LD.

Listing pages (blog index, categories) need markup as well, for example a CollectionPage with an ItemList.

Step 7: Generate sitemap.ts and robots.ts

app/sitemap.ts serves /sitemap.xml. The sitemap reference shows lastModified: new Date() in its examples; don’t copy that into production. It stamps every URL with the time the sitemap was generated, and Google’s sitemap guide only uses <lastmod> when it is consistently and verifiably accurate. Use content dates, and leave the field out where you have none.

// app/sitemap.ts
import type { MetadataRoute } from 'next'
import { getPublishedPosts } from '@/lib/posts'
import { NOINDEX_PATHS, SITE_URL } from '@/lib/site'
import { alternatesFor } from '@/lib/translations'

const STATIC_PAGES = ['/', '/about', '/blog']
const absolute = (path: string) => new URL(path, SITE_URL).href

export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
  const posts = await getPublishedPosts()
  const pages: { path: string; lastModified?: string }[] = [
    ...STATIC_PAGES.map((path) => ({ path })),
    ...posts.map((post) => ({ path: `/blog/${post.slug}`, lastModified: post.updatedAt ?? post.publishedAt }))
  ]

  return pages
    .filter(({ path }) => !NOINDEX_PATHS.includes(path))
    .map(({ path, lastModified }) => {
      const languages = alternatesFor(path)
      return {
        url: absolute(path),
        ...(lastModified ? { lastModified } : {}),
        ...(languages
          ? { alternates: { languages: { ...Object.fromEntries(Object.entries(languages).map(([lang, p]) => [lang, absolute(p)])), 'x-default': absolute(languages.en) } } }
          : {})
      }
    })
}
  • Same sources as the pages: the sitemap reads getPublishedPosts(), NOINDEX_PATHS and alternatesFor(), so it can’t list a draft, a noindex page or a different set of translations than the <head>. The sitemap lastmod guide covers what counts as a real update.
  • Skip changeFrequency and priority. Google’s sitemap guide says it ignores both.
  • Large sites: split with generateSitemaps. The reference says the files are served at paths like /product/sitemap/1.xml and notes Google’s limit of 50,000 URLs per sitemap. List each file in robots.txt or submit each in Search Console.
  • The reference also notes sitemap.ts is cached by default unless it uses request-time APIs or dynamic config.

app/robots.ts, from the robots reference:

// app/robots.ts
import type { MetadataRoute } from 'next'
import { SITE_URL } from '@/lib/site'

export default function robots(): MetadataRoute.Robots {
  return {
    rules: { userAgent: '*', allow: '/' },
    sitemap: new URL('/sitemap.xml', SITE_URL).href
  }
}

Don’t use robots.txt to keep pages out of search. Google’s noindex documentation says a page blocked in robots.txt can’t have its noindex seen. Keep noindex pages crawlable and let Step 3 mark them.

Step 8: Choose the URL format and set up redirects

Trailing slash. The trailingSlash reference says Next.js redirects /about/ to /about by default; trailingSlash: true reverses it, except for files with an extension and paths under .well-known/. Either works for Google as long as one form wins everywhere: config, canonical paths, internal links and sitemap. This guide keeps the default (no slash).

Redirects go in next.config. The redirects reference says permanent: true sends a 308 and false a 307, and Google’s HTTP status documentation treats 308 as equivalent to 301. Redirects run before the filesystem, including pages and public/ files.

// next.config.ts
import type { NextConfig } from 'next'

const config: NextConfig = {
  async redirects() {
    return [
      // The project's vercel.app domain answers too: send it to the real one.
      {
        source: '/:path*',
        has: [{ type: 'host', value: 'example.vercel.app' }],
        destination: 'https://example.com/:path*',
        permanent: true
      },
      { source: '/old-guide', destination: '/blog/new-guide', permanent: true },
      { source: '/old-blog/:slug', destination: '/blog/:slug', permanent: true }
    ]
  }
}

export default config

The reference’s pattern notes are worth reading before writing rules: /old-blog/:slug matches one segment only (/old-blog/a/b needs :slug*), and the slash before a parameter matters, or the path is treated as a literal string. Point each redirect at its final URL so changes don’t stack into chains.

On Vercel, preview deployments get an X-Robots-Tag: noindex header automatically, according to its guide to preview indexing; the guide doesn’t say the same for a production .vercel.app URL, which is why the host redirect above exists.

Static export. With output: 'export', the static exports guide lists redirects, rewrites, headers, Proxy, ISR and image optimization with the default loader as unsupported. Put redirects and headers in the host’s configuration, and with trailingSlash: true the export writes /about/index.html instead of /about.html.

Step 9: How do you add hreflang in the Next.js App Router?

Use one URL per language and a translation mapping that Steps 3 and 7 both read. The internationalization guide nests routes under app/[lang], prerenders locales with generateStaticParams and sets <html lang> from the lang param:

// app/[lang]/layout.tsx
export async function generateStaticParams() {
  return [{ lang: 'en' }, { lang: 'de' }]
}

export default async function RootLayout({ children, params }: LayoutProps<'/[lang]'>) {
  return (
    <html lang={(await params).lang}>
      <body>{children}</body>
    </html>
  )
}

The guide doesn’t generate hreflang for you. Map translated pages explicitly, because slugs often differ between languages:

// lib/translations.ts
/** One group per page; add a language only once that version is published. */
const GROUPS: Record<string, string>[] = [
  { en: '/en', de: '/de' },
  { en: '/en/about', de: '/de/ueber-uns' }
]

export function alternatesFor(path: string) {
  return GROUPS.find((group) => Object.values(group).includes(path)) ?? null
}

Because every page in a group prints the whole group, the output meets the rules in Google’s localized versions guide: each version lists itself and the others, links are reciprocal, x-default names the fallback, and URLs are absolute once metadataBase resolves them. Google treats the <head>, HTTP headers and sitemaps as equivalent; generating two of them from one mapping keeps them identical.

Be careful with automatic language redirects. The Next.js guide shows a Proxy that redirects visitors based on Accept-Language. Google’s guide to multi-regional and multilingual sites advises against automatically redirecting users between language versions, and says Googlebot usually crawls from the USA without setting Accept-Language. A crawler redirected that way only ever reaches one language. Keep every language reachable at its own URL, offer a language switcher or a suggestion banner, and if / must redirect, send everyone to the same default.

The hreflang errors guide covers missing return links, wrong codes and links to non-canonical pages.

Step 10: Images and social cards

Images. The Image component reference makes alt required and defaults loading to lazy. For the hero image that is likely your Largest Contentful Paint element, don’t leave it lazy. Since Next.js 16, priority is deprecated in favour of preload, and the reference adds that in most cases loading="eager" or fetchPriority="high" is the better choice:

import Image from 'next/image'
import hero from './hero.png'

<Image src={hero} alt="Crawl results grouped by issue" loading="eager" fetchPriority="high" />

The Largest Contentful Paint guide explains why a lazy hero image is slow.

Social cards. Put an opengraph-image.tsx in a route segment to generate the image with ImageResponse from next/og. The opengraph-image reference says generated images are created at build time and cached unless they use request-time APIs or uncached data, and Next.js adds the og:image tags, including width, height and alt. Both this file and openGraph.images in metadata produce og:image, so pick one source per route and drop images from the helper in Step 3 where a route has its own file. Load full font files for every script you publish, or accented and non-Latin titles can render wrong.

Step 11: Check the build before it ships

A Next.js app isn’t a folder of HTML files, so check the running production build. Start it, read the sitemap, and test each URL:

// scripts/check-seo.mjs: run against `next start`
const base = process.env.BASE_URL ?? 'http://localhost:3000'
const sitemap = await (await fetch(`${base}/sitemap.xml`)).text()
const paths = [...sitemap.matchAll(/<loc>([^<]+)<\/loc>/g)].map((m) => new URL(m[1]).pathname)

const errors = []
const titles = new Map()
const trim = (p) => p.replace(/\/$/, '')

for (const path of paths) {
  const res = await fetch(base + path, { redirect: 'manual' })
  if (res.status !== 200) {
    errors.push(`${path}: status ${res.status}`)
    continue
  }
  const html = await res.text()
  const head = html.split('</head>')[0]
  const canonical = head.match(/<link rel="canonical" href="([^"]+)"/)?.[1]
  if (!canonical) errors.push(`${path}: no canonical in <head>`)
  else if (trim(new URL(canonical).pathname) !== trim(path)) errors.push(`${path}: canonical is ${canonical}`)
  if (/<meta name="robots" content="[^"]*noindex/.test(html)) errors.push(`${path}: in the sitemap but noindex`)
  const title = head.match(/<title>([^<]*)<\/title>/)?.[1]
  if (!title) errors.push(`${path}: no <title> in <head>`)
  else if (titles.has(title)) errors.push(`${path}: same title as ${titles.get(title)}`)
  else titles.set(title, path)
  if ((html.match(/<h1[\s>]/g) ?? []).length !== 1) errors.push(`${path}: not exactly one <h1>`)
}

const missing = await fetch(`${base}/this-page-does-not-exist`)
if (missing.status !== 404) errors.push(`unknown URL returns ${missing.status}`)

if (errors.length) {
  console.error(errors.join('\n'))
  process.exit(1)
}
console.log(`SEO check passed for ${paths.length} URLs`)

Run it in CI on every pull request:

npm run build
npx next start -p 3000 &
until curl -s -o /dev/null http://localhost:3000; do sleep 1; done
node scripts/check-seo.mjs

Make it a required check before merging, so a page that loses its canonical or starts answering 200 for missing URLs never reaches production. Add rules as you find failure modes: description length, alt on images, JSON-LD that parses, hreflang targets that return 200.

After deploying:

  1. Curl a redirect source and a missing URL on the live domain, and confirm the status codes and Location headers.
  2. Submit https://example.com/sitemap.xml in Search Console, and use URL Inspection on a page per template to compare Google’s selected canonical with yours.
  3. Watch Page indexing for duplicates, soft 404s and “Crawled – currently not indexed”.
  4. Crawl the live site regularly. A crawler such as Crawlens fetches each page the way a search engine does and reports problems like redirect chains, non-indexable URLs in sitemaps, duplicate titles and hreflang without return links. With Render JavaScript on, it also shows content that only appears after scripts run.

Next.js SEO setup checklist

  • Page content renders on the server; nothing important depends on client-side fetching.
  • metadataBase and title.template in the root layout; no canonical, description or Open Graph defaults there.
  • One pageMetadata() helper sets canonical, robots, Open Graph and hreflang for every page.
  • Canonicals and titles are in the initial <head> (static metadata, or streaming metadata turned off).
  • One draft filter feeds pages, generateStaticParams and the sitemap.
  • Unknown slugs return a real 404: dynamicParams = false or notFound() before streaming starts.
  • JSON-LD per page type with < escaped; matches visible content.
  • sitemap.ts lists only indexable URLs, with lastModified from content dates.
  • robots.ts declares the sitemap and isn’t used to deindex.
  • One trailing-slash form; permanent redirects in next.config (or the host, for static exports).
  • hreflang from one mapping, with x-default; no automatic language redirects.
  • Hero image eager with high fetch priority; alt on every image; Open Graph images per route.
  • A check against next start in CI; live checks, Search Console and regular crawls after deploys.

Frequently asked questions

Is Next.js good for SEO?

Yes, when content is rendered on the server. App Router pages are Server Components by default and Client Components are prerendered to HTML, so the first response contains the page. Content fetched only in the browser, for example in useEffect, isn't in that HTML.

Does Next.js add canonical tags automatically?

No. Set alternates.canonical in each page's metadata, with metadataBase in the root layout so relative paths become absolute URLs. Don't set a canonical in the root layout: pages that don't override it inherit it.

Why does a missing page in Next.js return 200?

If notFound() runs after the response has started streaming, for example below a loading.js boundary, the status stays 200 and Next.js adds a noindex meta tag. Call notFound() before anything streams, or use dynamicParams = false so unknown slugs return a 404.

Should I redirect visitors to their language automatically?

Google advises against automatic redirects based on a guessed language, and says Googlebot usually crawls from the USA without an Accept-Language header. Use separate URLs per language with hreflang, and let visitors switch.

Do Next.js redirects work with a static export?

No. The static exports guide lists redirects, rewrites, headers and Proxy as unsupported with output: 'export'. Put redirects in your host's configuration instead.

· Founder, Crawlens

Dien builds Crawlens, a desktop crawler for technical SEO audits, and writes about the checks it runs: crawling, indexing, rendering and Search Console data.

Audit your own site with Crawlens

Crawl, run 70 checks, and see them next to Search Console and Core Web Vitals data.

Download free for Windows