SEO audits › Next.js
Next.js SEO checklist
Next.js gives you file conventions for the sitemap, robots.txt, metadata and 404s, but none of them are on by default and each has a way to go wrong without an error. This checklist covers what to implement and what to verify on the deployed site.
All code is for Next.js 16 with the App Router, checked against the current docs at nextjs.org. Where Next.js 15 behaves differently, the section says so.
Run a free audit on your Next.js site
All 140+ checks, no credit card. Last reviewed 2026-11-26.
Next.js SEO checklist: what to audit before and after deploy
Before deploy, confirm each item exists in the codebase. After deploy, confirm it in the HTML and headers the production URL returns, because that response is all a crawler has to go on. Most Next.js SEO bugs are a correct file that produces the wrong output in production: a canonical pointing at a preview host, a 404 page served with status 200, metadata that never reaches the <head>.
- Sitemap:
app/sitemap.tsexists, lists only canonical, indexable URLs, and/sitemap.xmlreturns 200 in production. - robots.txt:
app/robots.tsorapp/robots.txtexists, references the sitemap, and does not disallow/in production. - Canonicals:
metadataBaseis set in the root layout and every indexable page setsalternates.canonicalto its own URL. - noindex: previews and staging are noindexed, production is not.
- Meta tags: title and description appear in the server response for every route, not only after hydration.
- 404s: missing dynamic routes call
notFound()and the response status is 404, not 200. - Redirects: moved URLs return a 308 in one hop, with no chains.
- Structured data: JSON-LD is rendered by a Server Component and parses.
- Rendering: the main content and internal links are in the HTML before any JavaScript runs.
The pre-deploy half is a code review. The post-deploy half is a crawl: fetch every URL, follow every link, and compare what comes back against the list above.
Next.js sitemap: sitemap.ts, dynamic and multiple sitemaps (generateSitemaps)
Add app/sitemap.ts that default-exports a function returning an array of URL objects, and Next.js serves it at /sitemap.xml. For a small fixed site you can drop a hand-written app/sitemap.xml in the same place instead.
The function can be async, so a dynamic sitemap is a database or CMS query mapped to { url, lastModified }. sitemap.ts is a special Route Handler that is cached by default unless it uses a request-time API or dynamic config, so on a site whose content changes after the build, make sure it revalidates rather than serving the build-time list forever.
For multiple sitemaps, either nest files in route segments (app/sitemap.ts and app/products/sitemap.ts), or export generateSitemaps to split one segment into numbered files. Those are served at /.../sitemap/[id].xml, for example /products/sitemap/0.xml. Since v16.0.0 the id passed to the sitemap function is a promise that resolves to a string, so await it and convert it. In Next.js 15 it was a plain value.
app/products/sitemap.ts (Next.js 16, App Router)
import type { MetadataRoute } from 'next'
import { countProducts, getProducts } from '@/lib/products'
const BASE_URL = 'https://www.example.com'
const PER_FILE = 50000 // sitemap protocol limit per file
export async function generateSitemaps() {
const total = await countProducts()
const files = Math.max(1, Math.ceil(total / PER_FILE))
return Array.from({ length: files }, (_, id) => ({ id }))
}
export default async function sitemap(props: {
id: Promise<string>
}): Promise<MetadataRoute.Sitemap> {
const id = Number(await props.id)
const products = await getProducts({ offset: id * PER_FILE, limit: PER_FILE })
return products.map((product) => ({
url: `${BASE_URL}/products/${product.slug}`,
lastModified: product.updatedAt,
}))
}
// Served at /products/sitemap/0.xml, /products/sitemap/1.xml, ...
The docs describe only the per-id files for generateSitemaps, not a generated sitemap index, so list every file yourself. The sitemap field in robots.ts accepts an array.
Only put URLs in the sitemap that return 200, are indexable, and are their own canonical. The usual drift on a Next.js site is a sitemap built from the CMS while the route calls notFound() or redirect() for some of those records. Only set lastModified from a real modification date, not new Date() on every request.
Wrendex checks for this: Sitemap URL returns 4xx, Sitemap URL redirects, Sitemap URL is noindex, Sitemap URL non-canonical, URL missing from sitemap, Duplicate URL in sitemaps
Next.js robots.txt: static robots.txt and dynamic robots.ts
Put a plain robots.txt in the root of the app directory for a static file, or add app/robots.ts that returns a MetadataRoute.Robots object to generate it. Either way it is served at /robots.txt. Use one or the other, not both.
The dynamic version is worth it for one reason: you can block crawling on every environment except production from the same codebase. rules takes a single object or an array of per-user-agent objects, and sitemap takes a string or an array.
app/robots.ts (Next.js 16, App Router)
import type { MetadataRoute } from 'next'
const BASE_URL = 'https://www.example.com'
// VERCEL_ENV is set by Vercel. On other hosts, set your own variable.
const isProduction = process.env.VERCEL_ENV === 'production'
export default function robots(): MetadataRoute.Robots {
if (!isProduction) {
return { rules: { userAgent: '*', disallow: '/' } }
}
return {
rules: {
userAgent: '*',
allow: '/',
disallow: ['/api/', '/account/'],
},
sitemap: [
`${BASE_URL}/sitemap.xml`,
`${BASE_URL}/products/sitemap/0.xml`,
],
}
}
robots.ts is cached by default like sitemap.ts, so an environment check is evaluated at build time unless the route is dynamic. That is fine when each environment gets its own build, and wrong if you promote one build between environments.
If you use proxy.ts (called middleware.ts before v16), exclude robots.txt and sitemap.xml in its matcher. An auth redirect that catches /robots.txt makes the file unreachable for crawlers. The Pages Router has no robots.ts convention: put a static file in public/robots.txt.
A Disallow rule stops crawling, not indexing. To keep a page out of search results use noindex and leave the page crawlable so the tag can be read.
Wrendex checks for this: robots.txt inaccessible, Conflicting noindex signals
Canonical URLs with the Next.js Metadata API (alternates.canonical, metadataBase)
Next.js does not add a canonical tag for you. Set metadataBase once in the root layout, then set alternates.canonical in each page's metadata or generateMetadata. Relative canonicals are resolved against metadataBase, and a relative URL in a URL-based metadata field without a metadataBase is a build error.
Set the canonical per page, not in the root layout. A layout-level alternates: { canonical: '/' } is inherited by every route below it that does not define its own alternates, which tells search engines that every page on the site is a duplicate of the homepage.
app/layout.tsx and app/blog/[slug]/page.tsx (Next.js 16, App Router)
// app/layout.tsx
import type { Metadata } from 'next'
export const metadata: Metadata = {
metadataBase: new URL('https://www.example.com'),
title: { template: '%s | Example', default: 'Example' },
}
// app/blog/[slug]/page.tsx
import type { Metadata } from 'next'
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,
description: post.excerpt,
alternates: {
canonical: `/blog/${slug}`,
},
}
}
// Output:
// <link rel="canonical" href="https://www.example.com/blog/my-post" />
Metadata from layouts and pages is merged shallowly, so a nested object such as alternates or openGraph is replaced whole by the last segment that defines it. If a layout sets alternates.languages and the page sets only alternates.canonical, the hreflang links are gone on that page. Share nested values through a variable and spread them.
Hardcode the production origin in metadataBase or read it from a variable that always holds the production domain. Building it from the deployment URL puts preview hostnames into your canonicals. Build the canonical from the route params, not from searchParams, unless a query parameter really selects different content.
The canonical target must return 200 and match the URL form your site actually serves, including the trailingSlash setting. A canonical that redirects or 404s is ignored. A crawl finds these across the whole site faster than checking templates one at a time.
Wrendex checks for this: Duplicates without canonical, Canonical points to redirect, Canonical points to 4xx, Non-canonical declared as canonical, Canonical https to http, og:url and canonical disagree
Next.js noindex (metadata robots, per environment for previews)
Set robots: { index: false, follow: false } in a page's or layout's metadata and Next.js renders <meta name="robots" content="noindex, nofollow" />. In a layout it applies to every route below that does not set its own robots, which is how you noindex a whole section such as /account.
For previews and staging, set it in the root layout from an environment variable so one codebase is indexable in production and nowhere else.
app/layout.tsx (Next.js 16, App Router)
import type { Metadata } from 'next'
// VERCEL_ENV is 'production', 'preview' or 'development' on Vercel.
// On other hosts, set your own variable per environment.
const isProduction = process.env.VERCEL_ENV === 'production'
export const metadata: Metadata = {
metadataBase: new URL('https://www.example.com'),
robots: isProduction
? { index: true, follow: true }
: { index: false, follow: false },
}
On Vercel, preview deployments already get an X-Robots-Tag: noindex response header, and so do production deployments opened through their unique deployment URL. The header is not added when a preview is served from a custom domain assigned to a Git branch, such as staging.example.com. That case is the one that ends up in search results, and the metadata above covers it.
The failure in the other direction is worse: a noindex left on in production. It happens when the environment check reads a variable that is not set in the production build, or when a page-level robots object is copied from a draft template. Because robots is merged shallowly, a page that sets robots replaces the layout's value entirely.
To send the directive as a header instead, for non-HTML responses such as PDFs, return X-Robots-Tag from headers in next.config. Wrendex reports every page that carries a noindex, in the tag or the header, so you can confirm the list is the one you intended.
Wrendex checks for this: Page is noindex, Conflicting noindex signals, noindex, nofollow, Sitemap URL is noindex, Page became non-indexable
Custom 404 page in the App Router (not-found.tsx, notFound())
Create app/not-found.tsx and it renders for every URL that matches no route, as well as for any notFound() call that no nearer not-found file handles. Add a not-found.tsx inside a segment, such as app/blog/[slug]/not-found.tsx, for a 404 specific to that section.
A dynamic route matches any slug, so the route itself has to decide that a record does not exist. Call notFound() from next/navigation when the lookup comes back empty. Rendering an empty template or a "not found" message without calling it returns status 200.
app/blog/[slug]/page.tsx and app/not-found.tsx (Next.js 16, App Router)
// app/blog/[slug]/page.tsx
import { notFound } from 'next/navigation'
export default async function Page({
params,
}: {
params: Promise<{ slug: string }>
}) {
const { slug } = await params
const post = await getPost(slug)
if (!post) {
notFound() // throws, so nothing below runs
}
return <article>{/* ... */}</article>
}
// app/not-found.tsx
import Link from 'next/link'
export default function NotFound() {
return (
<main>
<h1>Page not found</h1>
<p>
<Link href="/">Back to the homepage</Link>
</p>
</main>
)
}
The status code depends on when notFound() runs. Before the response starts, Next.js returns a real 404. Once streaming has started the status is already sent as 200, and Next.js renders the not-found UI with <meta name="robots" content="noindex" /> instead. Without Cache Components, streaming starts as soon as a loading.tsx or <Suspense> fallback renders, so a loading.tsx above a dynamic route turns its 404s into noindexed 200s. With Cache Components, a request-time check inside the page runs after the shell is sent and also stays 200.
The noindex keeps those URLs out of search results, but other crawlers and your own monitoring will see 200. If you need the real status, do the existence check before streaming starts, or check the slug in proxy.ts and rewrite to a not-found route. Verify with curl -I on a URL that should not exist.
notFound() works by throwing. A try/catch around it swallows the 404, and a call inside a promise nobody awaits never renders the not-found UI. If the app has multiple root layouts, or a root layout under a dynamic segment such as app/[locale]/layout.tsx, the experimental global-not-found.tsx (v15.4.0 and later, behind experimental.globalNotFound) handles unmatched URLs. It must return a full document with <html> and <body>.
A 404 page is only half of it. The internal links that point at missing pages are what to fix, and a crawl lists each one with the page it was found on.
Wrendex checks for this: 404 Not Found, Links to broken page, Sitemap URL returns 4xx, Canonical points to 4xx
Next.js redirects: next.config redirects, redirect()/permanentRedirect(), proxy, and 307/308 vs 301
For a URL that has moved for good, use redirects in next.config.ts with permanent: true. It returns a 308, runs before the filesystem and before Proxy, and passes query strings through. Use redirect() and permanentRedirect() from next/navigation when the destination depends on data loaded during render, and NextResponse.redirect in proxy.ts when it depends on the request or you have more redirects than fit in config.
Next.js uses 307 and 308 where you might expect 302 and 301 because they preserve the request method. For search engines there is no penalty: Google treats 308 like 301, as a permanent redirect that makes the target canonical, and treats 302, 303 and 307 as temporary. The mistake to avoid is permanent: false, or a bare redirect(), on a page that has moved permanently.
next.config.ts, a page, and proxy.ts (Next.js 16, App Router)
// next.config.ts
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
async redirects() {
return [
// 308 Permanent Redirect
{ source: '/about-us', destination: '/about', permanent: true },
// Path parameters carry over
{ source: '/blog/:slug', destination: '/articles/:slug', permanent: true },
// Need a literal 301? Use statusCode instead of permanent, not both.
{ source: '/old-pricing', destination: '/pricing', statusCode: 301 },
]
},
}
export default nextConfig
// app/products/[id]/page.tsx
import { notFound, permanentRedirect } from 'next/navigation'
export default async function Page({
params,
}: {
params: Promise<{ id: string }>
}) {
const { id } = await params
const product = await getProduct(id)
if (!product) notFound()
if (product.mergedInto) {
permanentRedirect(`/products/${product.mergedInto}`) // 308
}
return <ProductPage product={product} />
}
// proxy.ts (named middleware.ts before v16)
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
export function proxy(request: NextRequest) {
const url = request.nextUrl.clone()
url.pathname = url.pathname.replace('/shop/', '/store/')
return NextResponse.redirect(url, 308)
}
export const config = {
matcher: '/shop/:path*',
}
redirect() returns 307 and permanentRedirect() returns 308, with two exceptions. In a Server Action they become a client-side navigation, or a 303 when the form is submitted without JavaScript. In a streaming context, where the response has already started, Next.js cannot send a redirect status and inserts a meta tag that redirects on the client instead. If a page's redirect has to be a real HTTP redirect, call it before anything streams, or move it to next.config.ts or Proxy. Both functions throw, so call them outside try blocks.
In v16 middleware.ts was renamed to proxy.ts and the exported function to proxy. The old name is deprecated, and npx @next/codemod@canary middleware-to-proxy . migrates it. Without a matcher, Proxy runs on every request including static assets.
Platforms can limit the size of the redirects array. Vercel's limit is 1,024, and the Next.js docs suggest a redirect map looked up in Proxy beyond about 1,000.
After adding redirects, update internal links to point at the final URL, and watch for chains between layers: a next.config.ts redirect whose destination is redirected again by the trailingSlash setting or by Proxy. Wrendex reports each chain, loop and temporary redirect with the pages that link to it.
Wrendex checks for this: Redirect chain, Redirect loop, 302 temporary redirect, Meta refresh redirect, Broken redirect, Links to redirected page, Sitemap URL redirects
Next.js structured data (JSON-LD)
Render JSON-LD as a native <script type="application/ld+json"> tag from the Server Component for the page or layout. That is the current recommendation in the Next.js docs. There is no metadata field for it, and next/script is the wrong tool because JSON-LD is data, not executable code.
JSON.stringify does not escape HTML, so a product name containing </script> would break out of the tag. Replace < with its unicode escape as below.
app/products/[id]/page.tsx (Next.js 16, App Router)
import { notFound } from 'next/navigation'
import type { Product, WithContext } from 'schema-dts'
export default async function Page({
params,
}: {
params: Promise<{ id: string }>
}) {
const { id } = await params
const product = await getProduct(id)
if (!product) notFound()
const jsonLd: WithContext<Product> = {
'@context': 'https://schema.org',
'@type': 'Product',
name: product.name,
image: product.image,
description: product.description,
offers: {
'@type': 'Offer',
price: product.price,
priceCurrency: 'USD',
availability: 'https://schema.org/InStock',
},
}
return (
<section>
<script
type="application/ld+json"
dangerouslySetInnerHTML={{
__html: JSON.stringify(jsonLd).replace(/</g, '\\u003c'),
}}
/>
<h1>{product.name}</h1>
</section>
)
}
schema-dts is a community package of schema.org types that the Next.js docs suggest. It catches misspelled properties at compile time. It does not know which properties Google requires for a rich result, so a block can type-check and still be ineligible.
Put site-wide entities such as Organization and WebSite in the root layout and page-specific ones in the page. Keep the values identical to what the page shows: a price in JSON-LD that differs from the visible price is a common result of caching the two separately.
Wrendex parses every JSON-LD block it finds and validates it against schema.org and Google's rich result requirements, page by page.
Wrendex checks for this: JSON-LD parse error, JSON-LD invalid @type, JSON-LD invalid property, Google rich result missing required field, Google rich result invalid value, JSON-LD missing @type
Client-rendered content that crawlers can't see
Content is visible to every crawler only if it is in the HTML the server sends. In the App Router that covers more than people expect: Client Components are prerendered on the server too, so 'use client' alone does not hide anything. What hides content is fetching it after hydration, or opting a component out of server rendering.
Googlebot runs JavaScript, but rendering is a separate, later step, and many other crawlers, link preview bots and AI crawlers read only the initial HTML. Treat anything that needs JavaScript to appear as optional.
- Data fetched in
useEffect, or by a client data library with no server prefetch. The server HTML contains the loading state and nothing else. Fetch in a Server Component and pass the result down as props. dynamic(() => import('./Reviews'), { ssr: false }). The component is skipped during prerender on purpose. Keep it for widgets that needwindow, not for content you want indexed.- Content that is only added to the DOM after a click: tabs, accordions and "load more" lists that render their panels conditionally. Render all panels and hide the inactive ones with CSS, or give each its own URL.
- Navigation built from
onClickandrouter.pushwith no<a href>. Crawlers follow links, not click handlers. Use<Link href>, which renders a real anchor. - Pagination or filters that exist only in client state. If page 2 has no URL, the items on it have no crawl path.
Before and after: move the fetch to the server (Next.js 16, App Router)
// Before: the server HTML is just <p>Loading...</p>
'use client'
import { useEffect, useState } from 'react'
export default function Reviews({ productId }: { productId: string }) {
const [reviews, setReviews] = useState<Review[] | null>(null)
useEffect(() => {
fetch(`/api/reviews?product=${productId}`)
.then((res) => res.json())
.then(setReviews)
}, [productId])
if (!reviews) return <p>Loading...</p>
return <ReviewList reviews={reviews} />
}
// After: a Server Component, so the reviews are in the response.
// ReviewList can still be a Client Component for sorting and voting.
export default async function Reviews({ productId }: { productId: string }) {
const reviews = await getReviews(productId)
return <ReviewList reviews={reviews} />
}
To check a page, run curl -s https://www.example.com/some-page and search the output for a sentence from the main content and for the href of a link you expect. Content streamed through <Suspense> passes this test: it is server-rendered and arrives later in the same response.
At site scale, the symptoms in a crawl of the raw HTML are pages with very little text, pages with no outgoing links, and pages that nothing links to even though they are in the sitemap. Wrendex crawls the raw HTML by default, which is what shows these up. JavaScript rendering is a per-site option if you also want to see what a rendering crawler gets.
Wrendex checks for this: Thin content, No outgoing internal links, Orphan page, URL missing from sitemap, H1 missing
Sources
- Next.js Docs: sitemap.xml file convention
- Next.js Docs: generateSitemaps
- Next.js Docs: robots.txt file convention
- Next.js Docs: Metadata files
- Next.js Docs: generateMetadata
- Next.js Docs: htmlLimitedBots
- Next.js Docs: not-found.js
- Next.js Docs: notFound
- Next.js Docs: loading.js, status codes
- Next.js Docs: How to handle redirects
- Next.js Docs: redirects in next.config.js
- Next.js Docs: redirect
- Next.js Docs: proxy.js
- Next.js Docs: How to implement JSON-LD
- Next.js Docs: Lazy loading
- Vercel Docs: Environments
- Vercel Docs: System environment variables
- Google Search Central: JavaScript SEO basics
- Google Search Central: Redirects and Google Search