Free SEO audit for new clients — claim yours
Home/Blog/Technical SEO/Next.js SEO: Metadata, Rendering and Sitemaps
Technical SEO

Next.js SEO: Metadata, Rendering and Sitemaps

Next.js SEO: Metadata, Rendering and Sitemaps
Table of contents
  1. Rendering modes in Next.js and what each means for crawling
  2. Titles, descriptions and canonicals with the Metadata API
    1. Static metadata for fixed pages
    2. generateMetadata for dynamic routes
  3. Generating sitemap.xml and robots.txt from code
  4. Redirects, status codes and trailing slashes
    1. Permanent redirects return 308, not 301
    2. Real 404s with notFound()
    3. Trailing slashes
  5. Images, fonts and scripts for Core Web Vitals
  6. Testing a Next.js site the way Googlebot sees it
  7. A worked example: auditing a Next.js product catalogue
  8. Questions developers ask about Next.js and search
    1. Is Next.js good for SEO?
    2. Should I use the App Router or Pages Router for SEO?
    3. Why do my Next.js redirects return 308 instead of 301?
    4. How do I add a canonical tag in Next.js?
    5. Does Next.js generate a sitemap automatically?
  9. Where to start on your Next.js SEO setup
  10. Further reading on nextjs seo
  11. Sources for this Next.js SEO guide

Next.js gives teams a lot of rendering power: static pages built ahead of time, pages rendered on every request, pages that regenerate in the background, and interactive client components layered on top. That flexibility is why so many marketing sites, SaaS products and headless stores run on it. It is also why Next.js SEO problems are so varied. The framework can produce perfectly crawlable HTML, or a page whose content, title and canonical only exist after JavaScript runs, depending on choices a developer made in a single file.

Most issues fall into a few buckets: the wrong rendering mode for content that needs to rank, metadata set in client components or not at all, missing or relative canonicals, redirects that return different status codes than the team expects, trailing slash inconsistencies, and sitemaps that list URLs the app does not actually serve.

This guide is a practical setup checklist for the App Router (with notes for the older Pages Router): which rendering mode to use for which page type, how to manage titles, descriptions and canonicals with the Metadata API, how to generate sitemaps and robots.txt, how redirects, status codes and trailing slashes behave, what the built-in image, font and script components do for Core Web Vitals, and how to test the site the way Googlebot sees it.

Rendering modes in Next.js and what each means for crawling

Google renders JavaScript, but it does so in a second step after crawling, and its guidance still favours HTML that arrives complete. On dynamic rendering, Google is blunt:

“Dynamic rendering is a workaround and not a recommended solution”

— Google Search Central, Dynamic rendering as a workaround

Instead, Google recommends server-side rendering, static rendering or hydration, which is exactly what Next.js is built to do. The question is which mode each route uses.

ModeApp RouterPages RouterHTML at request timeBest for
Static (prerendered at build)Default for Server Components without dynamic datagetStaticPropsComplete, from cacheMarketing pages, docs, blog posts
Incremental regenerationexport const revalidate = 3600 or tag-based revalidationgetStaticProps with revalidateComplete, refreshed in backgroundProduct and category pages, large catalogues
Dynamic (server-rendered per request)Triggered by cookies, headers, uncached fetches or dynamic = 'force-dynamic'getServerSidePropsComplete, built per requestSearch results, personalised pages, fast-changing data
Client-side only'use client' component fetching data in the browserFetching in useEffectShell only; content added by JSDashboards, account areas, non-indexable tools

The rule for SEO: anything you want indexed should be in the server-rendered HTML. Client components are fine for interactivity (a size selector, an accordion, a carousel), but the product name, description, price, headings and internal links should come from a Server Component or a server-rendered page. A common failure is a product page whose main content is a client component that fetches from an API on mount; View Source shows an empty container.

Static and regenerated pages also give you the fastest Time to First Byte, which helps LCP. Reserve fully dynamic rendering for pages that genuinely need per-request data. For the general trade-offs, our guide to server-side versus client-side rendering goes deeper.

Titles, descriptions and canonicals with the Metadata API

In the App Router, metadata is defined in layout or page files, which are Server Components, so tags are rendered on the server rather than injected by client JavaScript. There are two forms.

Static metadata for fixed pages

// app/layout.tsx
export const metadata = {
  metadataBase: new URL('https://www.example.com'),
  title: { default: 'Example Co', template: '%s | Example Co' },
  description: 'Project management software for construction teams.',
};

// app/pricing/page.tsx
export const metadata = {
  title: 'Pricing',               // renders "Pricing | Example Co"
  description: 'Plans for teams of 5 to 500.',
  alternates: { canonical: '/pricing' },
};

metadataBase in the root layout lets you write relative paths for canonicals and Open Graph images while Next.js outputs absolute URLs. That matters because Google recommends absolute URLs for canonicals (How to specify a canonical URL).

generateMetadata for dynamic routes

// app/products/[slug]/page.tsx
export async function generateMetadata({ params }) {
  const { slug } = await params;
  const product = await getProduct(slug);
  if (!product) return {};
  return {
    title: product.seoTitle ?? product.name,
    description: product.metaDescription,
    alternates: { canonical: `/products/${product.slug}` },
    openGraph: { images: [product.image.url] },
  };
}

Data fetching in generateMetadata and the page component is deduplicated when both use the same cached fetch, so you do not pay for the product query twice. Note that params is a promise in recent versions, hence the await; older versions pass it as a plain object.

Metadata checklist for every indexable route:

  • A unique title using the layout template, and a unique description .
  • A self-referencing alternates.canonical. Canonicals are not inherited sensibly from layouts; set them per page, or a layout-level canonical can point every child page at the home page.
  • Canonical URLs that strip tracking and sorting parameters, matching the trailing slash policy.
  • robots: { index: false } for thin or utility pages (internal search, filtered views you do not want indexed). Our internal site search pages guide covers when to noindex.
  • alternates.languages for hreflang on multilingual sites.

Recent Next.js versions can stream metadata for some browsers instead of blocking the initial HTML, while still placing it in the document head for known crawlers. If you rely on this, check what bots receive with the testing steps later in this guide, and if in doubt, confirm that the title and canonical are present in the raw HTML response.

Pages Router projects set these tags with next/head inside each page; the same principles apply, but make sure the tags render on the server, not only after a client-side fetch.

Generating sitemap.xml and robots.txt from code

The App Router supports special route files that generate these at build or request time.

// app/sitemap.ts
import type { MetadataRoute } from 'next';

export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
  const products = await getAllIndexableProducts();
  return [
    { url: 'https://www.example.com/', lastModified: new Date('2026-09-30') },
    ...products.map(p => ({
      url: `https://www.example.com/products/${p.slug}`,
      lastModified: p.updatedAt,
    })),
  ];
}

// app/robots.ts
export default function robots(): MetadataRoute.Robots {
  return {
    rules: { userAgent: '*', disallow: ['/api/', '/account/'] },
    sitemap: 'https://www.example.com/sitemap.xml',
  };
}

Google's sitemap documentation sets the rules your generated file must follow:

  • A single sitemap is limited to 50 MB uncompressed or 50,000 URLs. For larger catalogues, Next.js offers generateSitemaps to split output into multiple files; list them in a sitemap index or in robots.txt.
  • Use fully qualified absolute URLs.
  • Google ignores priority and changefreq, so do not bother computing them.
  • lastModified is only used if it is consistently accurate. Use the content's real update time, never new Date() at build time, which marks every URL as changed on every deploy.
  • Include only canonical, indexable URLs that return 200. Exclude noindexed and redirected routes.

Do not block /_next/static/ in robots.txt; Google needs those JavaScript and CSS files to render pages. More detail is in our XML sitemaps guide.

Redirects, status codes and trailing slashes

This is where Next.js behaviour most often surprises SEO teams.

Permanent redirects return 308, not 301

Redirects declared in next.config.js with permanent: true return a 308 status; permanent: false returns 307. The permanentRedirect() and redirect() functions used in server code behave the same way (308 and 307 by default). Google treats 308 as a permanent redirect equivalent to 301, so this is fine for SEO, but crawl tools and redirect maps should expect 308. Use statusCode: 301 in the config if a legacy system insists on it.

// next.config.js
module.exports = {
  async redirects() {
    return [
      { source: '/blog/:slug', destination: '/articles/:slug', permanent: true },
    ];
  },
};

For migrations with thousands of rules, config-based redirects can slow builds and routing; teams often move large maps into middleware backed by a key-value store. Either way, avoid chains (see our guide to redirect chains). Avoid client-side redirects with router.push for moved content; our article on meta refresh and JavaScript redirects explains why server redirects are stronger.

Real 404s with notFound()

Call notFound() in a page or generateMetadata when data does not exist; Next.js renders not-found.tsx with a 404 status. Without it, a dynamic route with an unknown slug may render an empty template with a 200 status, which Google reports as a soft 404. If the 404 decision happens after the response has started streaming, the status code can no longer change; Next.js then adds a noindex robots meta tag, which matches the fallback Google's JavaScript SEO guide describes for client-routed apps. Prefer resolving existence early, before streaming begins, so crawlers receive a true 404.

Trailing slashes

By default Next.js serves URLs without a trailing slash and redirects /pricing/ to /pricing. Setting trailingSlash: true reverses that. Pick one policy at launch and keep canonicals, sitemaps and internal links consistent with it. Switching after launch means redirecting every URL, so treat it as a migration.

SituationNext.js behaviourSEO implication
Config redirect, permanent: true308Treated as permanent; passes signals like a 301
Config redirect, permanent: false307Temporary; use only for genuinely temporary moves
notFound() before streaming404 with not-found UICorrect removal signal
notFound() after streaming starts200 with noindex metaUsually dropped from index, but slower and less clear
Unknown slug without notFound()200 with empty templateSoft 404s and thin pages
Default trailing slash policy/page/ redirects to /pageKeep canonicals and links slash-free

Routing should use real paths, never hash fragments; Google's URL structure guidance says not to use fragments to change page content. Our guide to URL fragments and SEO explains why.

Images, fonts and scripts for Core Web Vitals

Next.js ships components that solve common performance problems if you use them correctly.

  • Images (next/image). Generates srcset, serves modern formats through the image optimiser, requires dimensions (preventing layout shift) and lazy-loads by default. Two settings matter for LCP: pass an accurate sizes prop for fluid images, and mark the hero image as high priority so it is not lazy-loaded (the priority prop in most versions; newer releases have revised this API, so check the docs for yours). Web.dev's LCP guide explains why the LCP image should never be lazy-loaded. Background on the markup is in our guide to responsive images with srcset and sizes.
  • Fonts (next/font). Downloads Google Fonts at build time and self-hosts them, so no request goes to a third-party domain, and generates fallback metrics that reduce layout shift when the web font loads.
  • Scripts (next/script). Load analytics and tags with strategy="afterInteractive" or "lazyOnload" rather than in the head, to protect LCP and INP. Reserve beforeInteractive for scripts that genuinely must run first, such as consent managers.
  • JavaScript weight. Every 'use client' boundary ships JavaScript and hydration work. Keep client components small and at the leaves of the tree; heavy client bundles are the main cause of poor INP on Next.js sites.

Measure the result with field data. Next.js exposes a useReportWebVitals hook, or you can use Google's web-vitals library directly. Judge success against the Search Console thresholds of LCP 2.5 s, INP 200 ms and CLS 0.1 at the 75th percentile (Core Web Vitals report); our explainer on field data versus lab data shows how to read them.

Testing a Next.js site the way Googlebot sees it

Next.js development mode behaves differently from production (no static optimisation, extra dev scripts), so always test a production build or a preview deployment.

  1. View the raw HTML. Run curl -s https://www.example.com/products/oak-desk | grep -E "<title|canonical|<h1". The title, canonical and H1 should be present without JavaScript.
  2. Check status codes. curl -sI on a valid URL (200), a removed product (404), a moved page (308 or 301) and the non-preferred trailing slash variant (redirect).
  3. Disable JavaScript in DevTools and load key templates. Main content and navigation links should still be visible.
  4. Inspect in Search Console. Use the URL Inspection tool's live test to see the rendered HTML, screenshot, and any blocked resources or console errors, as Google's JavaScript troubleshooting guide recommends.
  5. Crawl the site with a crawler in both raw and rendered modes and compare word counts and link counts per template. Our guide to custom extraction shows how to pull titles, canonicals and schema at scale.
  6. Validate structured data with the Rich Results Test. Render JSON-LD in a Server Component with a <script type="application/ld+json"> tag rather than injecting it client-side.
  7. Check links are real anchors. Google can only discover links that are <a> elements with an href. The next/link component renders proper anchors; buttons with onClick navigation do not.

That last check is worth emphasising, because it is the most common crawlability bug in component-based sites. Google states it plainly:

“Google can only discover your links if they are <a> HTML elements with an href attribute.”

— Google Search Central, Understand the JavaScript SEO basics

A worked example: auditing a Next.js product catalogue

Hypothetical example for illustration. A furniture retailer moves 3,200 product pages and 140 category pages from a legacy platform to a Next.js App Router build. Four weeks after launch, Search Console shows only 1,900 product URLs indexed and 600 soft 404s.

FindingCauseFix
600 soft 404sDiscontinued slugs rendered an empty template with 200notFound() in page and generateMetadata; 308 redirects for discontinued items with a replacement
Product descriptions missing from raw HTMLDescription component marked 'use client' and fetched on mountFetch in the Server Component; keep only the variant picker client-side
All category pages canonicalised to /Canonical set in the root layoutPer-page alternates.canonical
Sitemap lastmod identical for all URLsnew Date() at buildUse product updatedAt
Mobile LCP 3.4 s on product pagesHero image lazy-loaded, no sizesHigh priority hero with accurate sizes

None of these are Next.js bugs; they are defaults and shortcuts that went unchecked. A pre-launch test pass using the steps above would have caught all five.

Is Next.js good for SEO?

Yes, when content that needs to rank is rendered on the server or statically. Google recommends server-side rendering, static rendering or hydration, all of which Next.js supports. Problems arise when key content lives only in client components.

Should I use the App Router or Pages Router for SEO?

Both can produce fully crawlable pages. The App Router's Server Components and Metadata API make it easier to keep content and tags on the server by default, so it is the better starting point for new projects.

Why do my Next.js redirects return 308 instead of 301?

Next.js uses 308 for permanent redirects and 307 for temporary ones. Google treats 308 as permanent, like 301. If another system requires a 301, set statusCode: 301 on the redirect.

How do I add a canonical tag in Next.js?

Set alternates.canonical in the page's metadata export or generateMetadata function, and define metadataBase in the root layout so Next.js outputs absolute URLs. Set it per page rather than in a shared layout.

Does Next.js generate a sitemap automatically?

Not by default. Add an app/sitemap.ts file that returns your indexable URLs, using real last-modified dates, and generateSitemaps to split catalogues above 50,000 URLs.

Where to start on your Next.js SEO setup

Pick your three most valuable templates, usually home, a category or listing page and a detail page, and run the testing checklist against a production build: raw HTML content, title and canonical, status codes for valid, missing and moved URLs, and LCP on mobile. Fix the patterns at template level, then generate the sitemap from the same data source that decides which pages exist. If your Next.js front end sits on a headless CMS, also review our headless CMS SEO guide, and for broader JavaScript issues see JavaScript SEO.

Launching or migrating a Next.js site? Our technical SEO team and web development team can review rendering, metadata and redirects before go-live. Get a quote and tell us your launch date.

Further reading on nextjs seo

Sources for this Next.js SEO guide

  1. Google Search Central: Understand the JavaScript SEO basics
  2. Google Search Central: Dynamic rendering as a workaround
  3. Google Search Central: Fix Search-related JavaScript problems
  4. Google Search Central: How to specify a canonical URL
  5. Google Search Central: Build and submit a sitemap
  6. Google Search Central: URL structure best practices
  7. web.dev: Optimize Largest Contentful Paint
  8. Search Console Help: Core Web Vitals report
  9. GoogleChrome/web-vitals on GitHub
Rohit Choudhary
Written byRohit ChoudharyCo-Founder, My SEO Experts

Rohit Choudhary is the co-founder of My SEO Experts and has more than 14 years of hands-on experience in SEO, paid advertising and digital marketing. Since starting out in 2011 he has helped hundreds of businesses grow through practical, data-driven search strategies, and he also serves as a consulting Digital Marketing Director for several US-based companies.

Keep reading

Related articles

Ready to grow your business online?

Get a free, no-obligation proposal tailored to your goals and budget.

CallFree Quote