SEO for Next.js comes down to making sure every indexable route ships complete HTML with the right title, description, canonical, and structured data, is listed in a sitemap, and loads fast. The App Router gives you built-in tools for each of these: the Metadata API and generateMetadata, sitemap.ts and robots.ts files, server rendering by default, and the next/image component. This guide shows how to use them correctly and how to verify the result on a live page.

How does Next.js affect SEO?
Next.js affects SEO through what it sends in the first HTML response. Because the App Router renders on the server by default, crawlers get real content and head tags without waiting for JavaScript. The framework handles the delivery; the values in those tags, the URLs you expose, and page speed are still your job.
Search engines judge a Next.js site the same way they judge any other site. What changes is where each SEO signal lives in your code. Titles and descriptions come from metadata exports. Canonicals and hreflang come from the alternates field. The sitemap and robots.txt are generated by special files in the app directory. Structured data is a script tag you render yourself. Performance depends on how you load images, fonts, and JavaScript.
That makes Next.js SEO mostly a configuration and review discipline. A single mistake in the root layout, such as a hardcoded canonical or a missing metadataBase, repeats on every route. A useful habit is to check new routes the way a crawler sees them: fetch the raw HTML, read the head, confirm the main text is present, and then run a rendered audit. The same logic underpins our broader JavaScript SEO guide, which covers frameworks in general.
This guide focuses on the App Router, which the current Next.js documentation treats as the default. The Pages Router uses different APIs (for example next/head and getStaticProps), so if you maintain an older project, the principles below still apply but the code does not. Every API example here was checked against the official Next.js documentation for version 16.4.0, the latest version listed at the time of writing.
Which rendering mode is best for Next.js SEO?
Any mode that puts the content in the server response works for SEO: static generation, Incremental Static Regeneration, or dynamic server rendering. Choose by how fresh the content must be. Avoid loading indexable content only through client-side fetching, which forces Google to render JavaScript before it sees anything.
Google's JavaScript SEO basics describe three phases: crawling, rendering, and indexing. Googlebot fetches the URL, extracts links from href attributes in the HTML, and queues the page for rendering. Content that is already in the HTML is available before that render step; content injected later depends on it. Google also notes that it will not render JavaScript from blocked files or on pages disallowed in robots.txt.
The App Router is helpful here. According to the Next.js documentation on Server and Client Components, Server Components are rendered into the RSC Payload on the server, and Client Components plus that payload are used to prerender HTML. On first load the browser shows that HTML immediately and then hydrates. In practice, a component marked "use client" still contributes its initial output to the HTML. The risk is data you fetch inside useEffect after hydration: that text is not in the response.
| Rendering approach | Good fit | What a crawler receives | Watch out for |
|---|---|---|---|
| Static generation (SSG) | Pages that rarely change: docs, landing pages, evergreen posts | Full HTML built ahead of time and served from cache | Content only updates when you rebuild or revalidate |
| Incremental Static Regeneration (ISR) | Large blogs, catalogs, listings that change on a schedule | Full HTML from cache, regenerated in the background | A visitor or bot may get the stale version until regeneration finishes |
| Dynamic server rendering (SSR) | Content that must be current on every request | Full HTML generated per request | Slow data fetching raises server response time |
| Client-side fetching only | Private dashboards and pages you do not need to rank | A shell first; content appears only after Google renders JavaScript | Risky for indexable pages and for crawlers that do not run JavaScript |
ISR deserves a note because it is popular for content sites. The Next.js ISR guide explains that with export const revalidate = 3600, a visitor arriving after the hour still receives the cached, stale page while a fresh version is generated in the background. The docs recommend a high revalidation time, such as an hour rather than a second, and on-demand revalidation when you need precision. For SEO, that means a just-edited title may take one more request to appear. For a deeper comparison of the trade-offs, see our server-side rendering SEO guide.
Links matter as much as content. Google can only discover links that are a elements with an href attribute, and it recommends the History API over URL fragments for client-side routing. The next/link component renders a real anchor, so use it for navigation instead of buttons with router.push in an onClick handler.
How do you set titles, descriptions, and social tags in Next.js?
Export a metadata object for static values or an async generateMetadata function for dynamic routes. Define metadataBase and a title template in the root layout, then let each page supply its own title, description, canonical, and Open Graph image. Both exports work only in Server Components.
The generateMetadata reference explains why: metadata must be resolved on the server before the page renders so that Next.js can include it in the initial HTML. If a page needs interactivity, keep page.tsx as a Server Component and move the interactive part into a separate client file. A typical setup looks like this:
// app/layout.tsx
import type { Metadata } from 'next'
export const metadata: Metadata = {
metadataBase: new URL('https://example.com'),
title: {
template: '%s | Example',
default: 'Example',
},
}
// app/blog/[slug]/page.tsx
import type { Metadata } from 'next'
export async function generateMetadata(
{ params }: { params: Promise<{ slug: string }> }
): Promise<Metadata> {
const { slug } = await params
const post = await getPost(slug)
return {
title: post.title, // -> "Post title | Example"
description: post.excerpt,
alternates: { canonical: '/blog/' + slug },
openGraph: { images: [post.coverImage] },
}
}Three behaviors cause most metadata bugs. First, title.template applies to child segments, not to the segment that defines it, and the docs require a default when you create a template. Second, metadata objects from layouts and pages are merged shallowly, so a page that sets openGraph with only a title replaces the entire openGraph object from the layout, including its image. Third, URL fields such as Open Graph images and canonicals need absolute URLs; metadataBase lets you write relative paths that Next.js composes into full URLs.
Since version 15.2, Next.js can stream metadata. The docs say the initial UI is sent without waiting for generateMetadata, and the tags are appended to the body when it resolves. Google is listed as a bot that executes JavaScript and reads the full DOM. For HTML-limited bots such as facebookexternalhit, Next.js detects the user agent and keeps metadata blocking so the tags land in the head. The htmlLimitedBots option in next.config lets you override that list.
Social previews are a good place to check this work. The capture below runs Rank Crown's OpenGraph checker on the Next.js 15 release post.

The result shows a well-configured page with two optional gaps. Both fields map to Metadata API keys (openGraph.siteName and twitter.site), so fixing them is a one-line change in the root layout. Write descriptions for people first; our meta description guide covers length and wording.
How do you handle canonical URLs in Next.js?
Set alternates.canonical for every indexable route, usually as a relative path resolved against metadataBase. Each page should output exactly one self-referencing canonical, and parameter variants such as tracking URLs should point back to the clean version.
In the metadata object, alternates.canonical produces a link rel="canonical" tag in the head. The Next.js docs show the composed output: with metadataBase set to https://acme.com and canonical set to '/', the tag becomes https://acme.com. Because generateMetadata receives the route params, you can build the canonical from the slug rather than from the incoming request, which keeps query strings such as utm_source out of it.
Google's JavaScript SEO documentation says it does not recommend injecting canonicals with JavaScript, and that if you do, the page must end up with only one rel="canonical" tag, because conflicting or multiple canonicals may lead to unexpected results. Server-rendered metadata avoids that problem entirely. Here is how a well-configured Next.js site behaves when you request a tracking-parameter URL:

That warning is the expected result for a parameter URL. The same check on the clean URL should report a self-referencing canonical. Run both variants whenever you change layouts, because a canonical defined in a parent layout and not overridden by the page will point every child route to the parent, a common way inner pages fall out of the index.
Canonicals are hints, not commands, and they work best alongside consistent internal links and redirects. Our canonical tag guide explains how search engines choose a canonical, and the duplicate content guide covers the other sources of duplicates, such as trailing slashes and filtered category pages.
How do you create sitemap.xml and robots.txt in Next.js?
Add app/sitemap.ts and app/robots.ts. Each exports a default function that returns a typed object (MetadataRoute.Sitemap or MetadataRoute.Robots), and Next.js serves the result as /sitemap.xml and /robots.txt. Generate sitemap entries from the same data source as your routes so the two never drift apart.
The sitemap file convention supports url, lastModified, changeFrequency, priority, images, and alternates.languages for localized URLs. The robots file convention accepts rules for one or several user agents and a sitemap URL. A minimal pair:
// app/sitemap.ts
import type { MetadataRoute } from 'next'
export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
const posts = await getAllPosts()
return [
{ url: 'https://example.com', lastModified: new Date() },
...posts.map((post) => ({
url: 'https://example.com/blog/' + post.slug,
lastModified: post.updatedAt,
})),
]
}
// app/robots.ts
import type { MetadataRoute } from 'next'
export default function robots(): MetadataRoute.Robots {
return {
rules: { userAgent: '*', allow: '/', disallow: '/account/' },
sitemap: 'https://example.com/sitemap.xml',
}
}For large sites, the docs describe two ways to split the sitemap: nest sitemap files in different route segments, or use generateSitemaps to return a list of ids and build one file per id. The docs' own example notes Google's limit of 50,000 URLs per sitemap and serves the parts at paths such as /product/sitemap/1.xml.
Keep lastModified honest. Setting it to new Date() for every URL on every build tells crawlers that everything changed, which makes the signal useless. Use the real update date from your CMS or database. Include only canonical, indexable URLs, and leave out redirects, noindex pages, and parameter variants.
On robots.txt, remember what it does and does not do. Disallowing a path stops crawling, not indexing, and Google will not render JavaScript from blocked files. Never disallow /_next/ or other asset paths that the page needs to render. Our robots.txt guide and XML sitemap guide go deeper, and you can validate the output with the free sitemap validator. The real nextjs.org robots.txt, for example, simply points to https://nextjs.org/sitemap.xml.
How do you add JSON-LD structured data to a Next.js page?
Render a script tag with type application/ld+json inside the page or layout component, building the object from the same data that renders the page. Escape the < character in the serialized string to prevent script injection, and validate the live URL after deploying.
The Next.js JSON-LD guide states that the current recommendation is to render structured data as a script tag in layout.js or page.js. It also warns that JSON.stringify does not sanitize strings used in XSS attacks and suggests replacing < with its unicode equivalent, \u003c, or using a maintained serializer such as serialize-javascript. That matters whenever a field comes from user input or a CMS.
// app/blog/[slug]/page.tsx
export default async function Page({ params }) {
const { slug } = await params
const post = await getPost(slug)
const jsonLd = {
'@context': 'https://schema.org',
'@type': 'BlogPosting',
headline: post.title,
datePublished: post.publishedAt,
author: { '@type': 'Person', name: post.authorName },
}
return (
<article>
<script
type="application/ld+json"
dangerouslySetInnerHTML={{
__html: JSON.stringify(jsonLd).replace(/</g, '\u003c'),
}}
/>
{/* page content */}
</article>
)
}Because the script is part of the server-rendered component, it appears in the initial HTML, not after hydration. You can see this pattern in production on the Next.js blog. The capture below runs Rank Crown's structured data checker on the Next.js 15 announcement.

Detection is only the first step. A checker confirms the markup is present and parseable; whether a type is eligible for a rich result depends on Google's documentation for that feature. Pick types that describe what the page actually shows, keep values consistent with visible content, and avoid marking up FAQs or reviews that are not on the page. Our schema markup guide covers type selection, and the structured data testing guide compares validators and explains how to read their errors and warnings.
How do you optimize images and Core Web Vitals in Next.js?
Use next/image with explicit dimensions or a correct sizes value, load the Largest Contentful Paint image eagerly, keep other images lazy, and trim client-side JavaScript. Then judge the result with field data, not just a lab score, against the Core Web Vitals thresholds.
web.dev defines the targets: Largest Contentful Paint within 2.5 seconds, Interaction to Next Paint of 200 milliseconds or less, and Cumulative Layout Shift of 0.1 or less, measured at the 75th percentile of page loads. The next/image reference covers the levers that matter most:
- Lazy by default. Images use native lazy loading unless you change it, which is right for below-the-fold content and wrong for the hero.
- preload replaces priority. Starting with Next.js 16, priority is deprecated in favor of preload. The docs add that in most cases loading="eager" or fetchPriority="high" is the better choice, and that preload should not be combined with them.
- sizes controls download weight. Without sizes, the browser assumes the image is as wide as the viewport, which can cause unnecessarily large downloads for fill or CSS-responsive images.
import Image from 'next/image'
// Hero image that is the LCP element
<Image src="/hero.jpg" alt="Product dashboard" width={1200} height={630} preload />
// Responsive image in a grid
<Image src={card.image} alt={card.alt} fill
sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw" />A lab audit shows where a page loses time. The capture below is Rank Crown's Lighthouse audit of the Next.js documentation homepage.

Even the framework's own docs carry a JavaScript cost in a simulated lab run: Total Blocking Time is the weak metric, while layout stability is perfect. Lab tests run one load on throttled hardware, so treat them as diagnostics. To see what real users experience, check field data from the Chrome UX Report, which PageSpeed Insights shows at the top of its report.

Note that the two captures test different URLs (the homepage versus /docs), so compare each page with itself over time rather than against each other. Our Core Web Vitals guide, website speed optimization guide, and render-blocking resources guide cover the fixes, and lazy loading and SEO explains when deferring images helps and when it hurts. For alt text and file formats, see the image SEO guide.
How do you set up hreflang for a multilingual Next.js site?
Give each language its own URL, usually with a locale sub-path or domain, then declare every version through alternates.languages in metadata or in sitemap.ts. Each version must list itself and all the others with fully qualified URLs, or Google ignores the annotations.
The Next.js internationalization guide describes routing by sub-path (/fr/products) or by domain (my-site.fr/products), with locale detection done in Proxy using the Accept-Language header. For SEO, be careful with automatic redirects based on that header: a crawler requesting /products should still be able to reach every language version through normal links.
The Metadata API turns alternates.languages into link rel="alternate" hreflang tags. The Next.js docs show a layout with en-US and de-DE entries producing exactly those tags, composed against metadataBase. If you prefer to keep hreflang out of the head, sitemap.ts accepts the same alternates.languages structure and outputs xhtml:link entries for each URL.
Whichever method you choose, follow Google's localized versions guidelines. Each language version must list itself as well as all other versions. Alternate URLs must be fully qualified, including https. If two pages do not point to each other, the tags are ignored. Google also suggests a generic fallback, such as an en page for English speakers outside your specific locales.
The most frequent Next.js bug here is building the language map in one layout and forgetting that the page overrides alternates for its canonical. Because metadata merges shallowly, setting alternates: { canonical } in a page drops the languages defined above it. Return canonical and languages together from the same generateMetadata. Our hreflang guide covers region codes and x-default.
What are the most common Next.js SEO mistakes?
Most Next.js SEO problems come from content loaded only on the client, metadata that is overwritten by shallow merging, wrong canonicals inherited from layouts, missing pages that return 200, and slow LCP images. Each one is visible in the raw HTML or a quick audit.
| Mistake | What you see | Fix |
|---|---|---|
| Fetching main content in useEffect | Raw HTML has an empty shell or a spinner | Fetch in a Server Component so the text is in the initial HTML |
| Defining openGraph in a layout and a partial openGraph in a page | Page loses the og:image set in the layout | Repeat the full nested object, or share it from a constant |
| Relative image or canonical URLs without metadataBase | Open Graph images or canonicals without a usable absolute URL | Set metadataBase once in the root layout |
| Canonical on every page pointing to the homepage | Inner pages drop out of the index | Use a self-referencing canonical per route |
| Navigation built with onClick handlers instead of links | Google does not discover deeper pages | Use next/link, which renders a real a element with an href |
| Missing pages return 200 with a 'not found' message | Soft 404 reports in Search Console | Call notFound() for missing records |
| Preview or staging deployment left indexable | Duplicate copies of the site appear in search | Block it with authentication or a noindex robots setting |
| Above-the-fold hero image lazy-loaded | Slow Largest Contentful Paint | Use preload, loading="eager" or fetchPriority="high" on the LCP image |
Soft 404s deserve their own mention. Google's JavaScript SEO page warns that client-side routing often makes meaningful status codes impractical and that pages which say "not found" but return success can be treated as soft 404s. In the App Router, call notFound() from next/navigation when a record does not exist, so the route renders your not-found UI instead of an empty template.
Also check noindex handling. Google notes that when it encounters a noindex tag, it may skip rendering and JavaScript execution, so removing noindex later with client-side code does not work. Set robots values in metadata on the server. After fixing issues, confirm that Google can actually index the pages; the Google indexing guide walks through the URL Inspection workflow, and the crawl budget guide helps on large ISR catalogs.
Finally, make the review repeatable. A crawl of the whole site catches the patterns that single-page checks miss, such as a template that ships the same title on hundreds of routes. Rank Crown's site audit runs that kind of crawl, and the technical SEO checklist gives you the full list to work through before each major release.
Frequently Asked Questions
Is Next.js good for SEO?
Yes, mainly because the App Router renders pages on the server by default, so the HTML a crawler receives already contains your content, title, and links. Next.js does not rank a site by itself, though. You still need correct metadata, canonicals, a sitemap, crawlable links, and fast pages, and those are configuration choices you make in your code.
Does Google index client components in Next.js?
Usually, yes. In the App Router, Client Components are still prerendered to HTML on the server and then hydrated in the browser, so their initial output is in the HTML. Content that only appears after a client-side fetch or a user interaction is different, because Google has to render the page to see it, so keep important text in the server-rendered output.
How do I add a canonical tag in Next.js?
Set alternates.canonical in the metadata object or in generateMetadata for the route. If you define metadataBase in the root layout, you can pass a relative path such as '/blog/my-post' and Next.js composes the absolute URL in a link rel="canonical" tag. Make sure each page outputs exactly one canonical and that it points to the clean, indexable URL.
What is the difference between metadata and generateMetadata?
The static metadata export is a plain object for values known at build time, such as a fixed title on an About page. generateMetadata is an async function that receives route params and can fetch data, so it suits dynamic routes like blog posts or products. Both are only supported in Server Components, so metadata is resolved on the server and included in the HTML.
Do I still need next-sitemap with the App Router?
Not for most sites. The App Router supports a sitemap.ts file that returns an array of URLs and generates sitemap.xml, plus generateSitemaps for splitting large sites into several files. A robots.ts file covers robots.txt the same way. A third-party package can still help if you need features the built-in files do not provide.
Should I use SSR, SSG, or ISR for SEO?
Any of them gives crawlers full HTML, which is the part that matters for indexing. Choose by how often the content changes: static generation for pages that rarely change, ISR for large catalogs or blogs that update periodically, and dynamic server rendering for content that must be current on every request. Avoid pure client-side rendering for pages you want to rank.
How do I add JSON-LD structured data in Next.js?
Next.js recommends rendering JSON-LD as a script tag with type application/ld+json inside your layout or page component. Build the object in code, serialize it with JSON.stringify, and replace the < character with its unicode escape so injected strings cannot break out of the script tag. Then test the live URL with a structured data validator.
Why does my Next.js page show the wrong title in search or social previews?
Common causes are a child segment that overwrites a nested field, because metadata objects merge shallowly, a missing title.template in the root layout, or relative image URLs without metadataBase. Social crawlers that do not run JavaScript also need tags in the head, which Next.js handles for known HTML-limited bots. Fetch the page as raw HTML and read the tags.
Audit your Next.js site the way a crawler sees it
Crawl every route to find missing titles, duplicate canonicals, broken links, and slow pages before they cost you rankings.
Explore the site audit