Next.js SEO Guide for the App Router

Front-end developer pair-programming with an SEO lead at a desk

Next.js SEO on the App Router comes down to a handful of built-in features. The Metadata API writes your titles, descriptions and canonicals. The sitemap.ts and robots.ts files generate crawl files. Your rendering choice decides what HTML a crawler receives on the first request. Get those right and most of the framework-specific risk disappears.

This guide is written against Next.js 16, the version search.agency runs on as of December 2026. Every API name below was checked against the Next.js docs that ship with that version. Where we describe a choice we made on our own site, we say why.

Is Next.js good for SEO?

Yes, with one condition. Server components, static generation and server rendering all put real content in the initial HTML. Search engines and AI crawlers can read that HTML without running JavaScript. The risk comes from pages that fetch their main content in the browser after load. Googlebot renders JavaScript in a second pass, which can delay indexing, as our post on Googlebot's render queue explains. Many AI crawlers don't render JavaScript at all. Our guide to JavaScript fallbacks for AI crawlers covers what they miss.

A quick test works for any route. Run curl against the URL and search the raw response for your H1 and first paragraph. If they're missing, the page depends on client-side rendering for its content.

Titles, descriptions and canonicals with the Metadata API

The App Router has two ways to set metadata. A static metadata object suits pages whose tags never change. The async generateMetadata function suits dynamic routes such as blog posts and product pages, where tags come from your CMS or database. Both are covered in the generateMetadata reference.

Set metadataBase and a title template in the root layout

Put metadataBase in app/layout.tsx. It lets every canonical and Open Graph URL below it be a relative path. The docs note that a relative URL field without metadataBase causes a build error.

The root layout is also the place for a title template.

export const metadata = {
  metadataBase: new URL('https://example.com'),
  title: {
    template: '%s | Example',
    default: 'Example',
  },
}

A page that sets title: 'Pricing' then renders as "Pricing | Example". Three rules from the docs catch people out.

  • Templates apply only to child segments. They have no effect on a page in the same segment as the layout that defines them.
  • title.default is required whenever you add a template.
  • title.absolute ignores every parent template.

We use title.absolute on blog posts. Our root layout appends the brand to service pages. Post titles skip the suffix to keep the full character budget for the headline.

Canonicals through alternates

Set the canonical with alternates.canonical. In a generateMetadata function for app/blog/[slug]/page.tsx, that looks like this.

export async function generateMetadata({ params }) {
  const { slug } = await params
  const post = await getPost(slug)
  return {
    title: post.seoTitle,
    description: post.excerpt,
    alternates: { canonical: `/blog/${slug}` },
  }
}

Note that params is a Promise in current versions and must be awaited. Older tutorials read it synchronously.

Streaming metadata and the htmlLimitedBots setting

Current Next.js can stream metadata. The page starts rendering before generateMetadata resolves. The tags arrive later in the <body>. The docs say this works for bots that execute JavaScript, such as Googlebot. Bots on Next.js's list of HTML-limited crawlers still get blocking metadata in the <head>.

That list is matched on user agent. A crawler missing from it gets the streamed version. On search.agency we set htmlLimitedBots: /.*/ in next.config.ts, which the htmlLimitedBots docs give as the way to disable streaming metadata entirely. Every visitor and every crawler gets the title, description and canonical in the head. The cost is a slightly later first byte on routes with slow metadata. For a content site we take that trade.

How to create a sitemap in Next.js

Add app/sitemap.ts and export a default function that returns an array of URLs. Next.js serves the result at /sitemap.xml. The sitemap file convention types the return value as MetadataRoute.Sitemap.

import type { MetadataRoute } from 'next'

export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
  const posts = await getAllPosts()
  return posts.map((p) => ({
    url: `https://example.com/blog/${p.slug}`,
    lastModified: p.updatedAt,
  }))
}

A few details matter for search.

  • Caching. The docs describe sitemap.ts as a special Route Handler that is cached by default. If posts are published from a CMS, add a revalidation period. Without one, new URLs won't appear until the next build. Our sitemap revalidates every 60 seconds.
  • Large sites. Google caps a single sitemap at 50,000 URLs or 50MB uncompressed. Next.js offers generateSitemaps to split one route into several files by ID.
  • Extras. Each entry accepts images, videos and alternates.languages for image, video and hreflang sitemaps.

Make lastModified honest

Many Next.js sitemaps go wrong here. Setting lastModified: new Date() stamps every URL with the build or request time. Google's sitemap documentation says it uses lastmod only when the value is consistently and verifiably accurate. It also ignores priority and changefreq, which Next.js still accepts as priority and changeFrequency.

Our sitemap takes three approaches. Blog posts use their stored edit date. Static pages carry a hand-set date in a map, updated in the same commit as the copy change. Listing pages such as the blog index take the newest edit date among the posts they show. We also list only the first page of each blog category. Paginated archives stay reachable through their own links. In October 2026, 33 of those paginated URLs were among the 70 sitemap URLs Search Console listed as unindexed.

robots.ts in Next.js

The robots file convention works the same way. Export a function from app/robots.ts that returns MetadataRoute.Robots. The object holds your rules and a sitemap URL.

Two habits from our own file are worth copying. We give the main AI crawlers, including GPTBot, ClaudeBot and PerplexityBot, explicit rule blocks that mirror the catch-all. That removes any ambiguity about access. We also block tracking parameters by name. An earlier blanket rule against every query string hid our blog images from crawlers, because our image CDN URLs carry query strings. Narrow rules avoid that kind of collateral damage.

Open Graph images in Next.js

You have two routes. One is openGraph.images in your metadata. The other is an opengraph-image file in a route folder. That file can be a static image or an opengraph-image.tsx that draws a card with ImageResponse from next/og. A more specific file deeper in the folder tree takes precedence over one higher up.

The generateMetadata reference states that file-based metadata "has the higher priority and will override the metadata object and generateMetadata function." Our own build behaved the opposite way. The blog post route on search.agency has both an opengraph-image.tsx file and a generateMetadata that sets openGraph.images. On Next.js 16.4.5 the openGraph.images value replaced the file-based image. Posts such as our ChatGPT ads guide serve their stored cover JPEG as the og:image. If you combine the two on one route, confirm the rendered tag in view-source on your own build before you ship. Social platforms cache cards. A wrong image can linger after you fix it.

Structured data with JSON-LD

Next.js has no metadata field for structured data. The JSON-LD guide recommends rendering a <script type="application/ld+json"> tag inside your layout or page component.

One detail is easy to miss. JSON.stringify leaves < unescaped. A CMS value containing </script> could break out of the tag. The docs suggest replacing < with its unicode equivalent, \u003c. Our shared JSON-LD component escapes <, > and & before rendering. Validate the output with Google's Rich Results Test or the Schema Markup Validator.

Static, dynamic or ISR and what crawlers see

RenderingHow it worksCrawl effect
StaticHTML built ahead of time, often with generateStaticParams for dynamic routesFastest response. Content is in the HTML. Updates need a rebuild or revalidation
ISRStatic HTML regenerated in the background after a revalidation period or on demandStatic speed with fresh content. Good default for blogs and catalogs
DynamicHTML rendered per request on the serverContent is in the HTML. Response time depends on your data sources
Client-side fetchContent loaded in the browser after hydrationMissing from the initial HTML. Googlebot sees it after rendering. Many AI crawlers never do

Our blog post route prerenders every slug with generateStaticParams and revalidates every 60 seconds. A CMS edit reaches the live page within a minute without a full rebuild.

Next.js 16 also offers Cache Components, an opt-in model built on the use cache directive. The ISR guide has separate instructions for projects with and without it. Follow the one that matches your config.

The streaming status code trap

The streaming guide documents a problem that matters for SEO. Once a loading.tsx fallback or a Suspense boundary starts the stream, the server has already sent 200 OK. A notFound() call after that point can't change the status. Next.js injects a noindex meta tag in its place. A redirect() mid-stream becomes a client-side redirect with no HTTP redirect header.

Either way the page stays out of the index. Your logs and crawl tools will report a 200 for a page that doesn't exist. The docs give the fix. Call notFound() before any await or Suspense boundary. Check that the slug exists first and stream the rest after.

Redirects in next.config

Define server-side redirects in the redirects function of next.config.ts. Each entry takes a source, a destination and a permanent flag. Per the redirects reference, permanent: true returns a 308 and false returns a 307. Google's redirect documentation lists 308 alongside 301 as a permanent move.

Config redirects run before the page renders. That keeps a real status code, which avoids the streaming problem above. When we merged 39 low-demand blog posts into 23 topic hubs in late 2026, each retired slug got a permanent entry pointing at its hub.

Hreflang and internationalization

In the App Router you build locale routing yourself. The internationalization guide uses a dynamic [lang] segment and a proxy.ts file (formerly middleware) to route visitors by locale.

For hreflang, pass alternates.languages in your metadata. Next.js renders each entry as a <link rel="alternate" hreflang> tag. Google's localized versions guide requires each language version to list itself and every other version. Return links matter. Google ignores the tags when two pages don't both point to each other. Add an x-default entry for visitors whose language matches no version.

Avoid redirecting visitors to a locale automatically based on Accept-Language without an escape route. Google's locale-adaptive pages guide says Googlebot sends requests without that header. A forced redirect can leave some language versions uncrawled.

Core Web Vitals with next/image and next/font

The next/image component sizes, lazy-loads and serves responsive images. In Next.js 16 the priority prop is deprecated in favor of preload. For most LCP images the Image reference recommends loading="eager" or fetchPriority="high" over preload. Set sizes on responsive images. Without it the browser assumes the image spans the full viewport and can download a larger file than the layout needs.

Next.js also documents a loaderFile option for handing image optimization to a cloud provider. We use it to point next/image at our image CDN. Whichever host you deploy to, check that image requests return resized files before you rely on them.

next/font self-hosts Google Fonts and local font files. The fonts docs say the browser sends no requests to Google when a visitor loads your site. That removes a third-party connection from the critical path and reduces layout shift from late font swaps.

Next.js SEO checklist

AreaCheck
Root layoutmetadataBase set, title template with a default
Dynamic routesgenerateMetadata returns title, description and alternates.canonical
Crawl filessitemap.ts with real edit dates and a revalidation period, robots.ts pointing to it
HTMLMain content present in the raw response for every indexable route
Status codesnotFound() runs before streaming starts, retired URLs redirect in config
Structured dataJSON-LD script with < escaped, validated in the Rich Results Test
PerformanceLCP image eager or high priority, sizes set, fonts through next/font

If your site was generated by an AI app builder on top of Next.js or React, our guide to optimizing a vibe coded website covers the extra gaps those tools leave. For a review of your own stack, our technical SEO team can audit the rendered output route by route.

Want this for your brand

See where your brand stands in AI answers today, benchmarked against your competitors, no pitch required.