AboutProjectsWorkBlogContact
Home / Blog / Next.js, React & TypeScript

Implementing SEO-Friendly Dynamic Routes in Next.js

Static params, metadata, canonicals and a sitemap: the full SEO setup for [slug] routes.

By Hamza JanzaibNovember 28, 202611 min readIntermediate
Paste it into ChatGPT, Claude or any AI assistant.
  • next.js
  • seo
  • routing
  • metadata
On this page · 13 sections
  • What search engines need from a dynamic route
  • Step 1: Prerender the routes with generateStaticParams
  • Step 2: Read params correctly
  • Step 3: Generate unique metadata per page
  • Step 4: Set metadataBase once
  • Step 5: Add a sitemap and robots file
  • Step 6: Add structured data
  • Step 7: Generate Open Graph images
  • Common mistakes
  • Internal linking
  • Testing and validation
  • Best practices
  • Conclusion

A dynamic route like /blog/[slug] can rank just as well as any hand-written page, but only if it behaves like a hand-written page: unique HTML, a real status code, its own title and description, a stable canonical URL and a place in the sitemap. This guide shows how to wire all of that up in the Next.js App Router, including the new requirements that come with params being asynchronous and Cache Components.

What search engines need from a dynamic route

RequirementHow you provide it
Real HTML on first responseServer Components with prerendering
A real 404 for unknown pagesnotFound()
Unique title and descriptiongenerateMetadata
One canonical URL per pagealternates.canonical + metadataBase
DiscoverabilityInternal links and sitemap.ts
Rich results and contextJSON-LD (Article, BreadcrumbList)
Social previewsOpen Graph and Twitter metadata, OG images

Step 1: Prerender the routes with generateStaticParams

generateStaticParams tells Next.js which values of the dynamic segment to build ahead of time:

tsx
// app/blog/[slug]/page.tsximport { getPublishedPosts } from "@/lib/blog";export function generateStaticParams() {  return getPublishedPosts().map((post) => ({ slug: post.slug }));}

Prerendered pages are served as static HTML, which is fast and gives crawlers complete content immediately.

Step 2: Read params correctly

params is a Promise. With Cache Components enabled, reading it is treated as request-dependent data, so the component that awaits it must sit inside a <Suspense> boundary. A clean way to do that is a thin page component plus an async inner component:

tsx
// app/blog/[slug]/page.tsximport { notFound } from "next/navigation";import { Suspense } from "react";import { getPost } from "@/lib/blog";export default function Page({ params }: PageProps<"/blog/[slug]">) {  return (    <Suspense fallback={null}>      <BlogPostPage params={params} />    </Suspense>  );}async function BlogPostPage({  params,}: {  params: PageProps<"/blog/[slug]">["params"];}) {  const { slug } = await params;  const post = getPost(slug);  if (!post) notFound();  return (    <article>      <h1>{post.title}</h1>      {/* … */}    </article>  );}

Two details matter for SEO here:

  • notFound() produces a true 404 response, which keeps deleted or mistyped URLs out of the index.
  • With generateStaticParams, the known slugs are prerendered, so the shell and content of real posts are in the HTML.

Use a meaningful fallback, or null when the content is fully prerendered and the boundary is only a technical requirement.

Step 3: Generate unique metadata per page

generateMetadata receives the same params and returns the tags for that page:

tsx
import type { Metadata } from "next";export async function generateMetadata({  params,}: PageProps<"/blog/[slug]">): Promise<Metadata> {  const { slug } = await params;  const post = getPost(slug);  if (!post) return {};  const url = `/blog/${post.slug}`;  return {    title: { absolute: post.seoTitle },    description: post.metaDescription,    keywords: [post.primaryKeyword, ...post.secondaryKeywords],    alternates: { canonical: url },    openGraph: {      type: "article",      url,      title: post.seoTitle,      description: post.metaDescription,      publishedTime: post.publishedAt,      tags: post.tags,    },    twitter: {      card: "summary_large_image",      title: post.seoTitle,      description: post.metaDescription,    },  };}

Guidelines for the values themselves:

  • Title: roughly 50 to 60 characters, primary keyword near the start, unique per page.
  • Description: roughly 120 to 160 characters, written for humans, ending with a reason to click.
  • Canonical: one URL per page, even if the same content is reachable via query strings.

Use title: { absolute: ... } when you do not want the root layout's title template appended.

Step 4: Set metadataBase once

Relative URLs in metadata (canonical, Open Graph images) need a base so they resolve to absolute URLs:

tsx
// app/layout.tsximport type { Metadata } from "next";export const metadata: Metadata = {  metadataBase: new URL(process.env.NEXT_PUBLIC_APP_URL ?? "http://localhost:3000"),  title: { default: "My Site", template: "%s | My Site" },};

Set NEXT_PUBLIC_APP_URL to your production origin. A localhost base in production is a common cause of wrong canonicals and sitemap entries.

Step 5: Add a sitemap and robots file

Generate the sitemap from the same data source as the routes so they never drift apart:

ts
// app/sitemap.tsimport type { MetadataRoute } from "next";import { getPublishedPosts } from "@/lib/blog";const base = (process.env.NEXT_PUBLIC_APP_URL ?? "http://localhost:3000").replace(/\/$/, "");export default function sitemap(): MetadataRoute.Sitemap {  const posts = getPublishedPosts();  return [    { url: base },    { url: `${base}/blog` },    ...posts.map((p) => ({      url: `${base}/blog/${p.slug}`,      lastModified: p.updatedAt ?? p.publishedAt,    })),  ];}
ts
// app/robots.tsimport type { MetadataRoute } from "next";export default function robots(): MetadataRoute.Robots {  const base = (process.env.NEXT_PUBLIC_APP_URL ?? "http://localhost:3000").replace(/\/$/, "");  return {    rules: { userAgent: "*", allow: "/", disallow: "/api/" },    sitemap: `${base}/sitemap.xml`,  };}

Submit the sitemap URL in Google Search Console, then monitor indexing and coverage there.

Step 6: Add structured data

JSON-LD gives search engines explicit context. Render it as a script tag, and escape < so injected strings cannot break out of the script:

tsx
const jsonLd = [  {    "@context": "https://schema.org",    "@type": "BlogPosting",    headline: post.title,    description: post.metaDescription,    datePublished: post.publishedAt,    author: { "@type": "Person", name: "Your Name" },    mainEntityOfPage: `${site}/blog/${post.slug}`,  },  {    "@context": "https://schema.org",    "@type": "BreadcrumbList",    itemListElement: [      { "@type": "ListItem", position: 1, name: "Home", item: site },      { "@type": "ListItem", position: 2, name: "Blog", item: `${site}/blog` },      { "@type": "ListItem", position: 3, name: post.title, item: `${site}/blog/${post.slug}` },    ],  },];return (  <script    type="application/ld+json"    dangerouslySetInnerHTML={{      __html: JSON.stringify(jsonLd).replace(/</g, "\\u003c"),    }}  />);

Only mark up what is actually on the page. Validate with Google's Rich Results Test. Add FAQ markup only when it is appropriate under Google's current policies.

Step 7: Generate Open Graph images

A file named opengraph-image.tsx next to the dynamic page can render a unique image per slug:

tsx
// app/blog/[slug]/opengraph-image.tsximport { ImageResponse } from "next/og";import { getPost } from "@/lib/blog";export const size = { width: 1200, height: 630 };export const contentType = "image/png";export default async function Image({ params }: { params: Promise<{ slug: string }> }) {  const post = getPost((await params).slug);  return new ImageResponse(    (      <div style={{ display: "flex", width: "100%", height: "100%", padding: 72, background: "#0a0a0a", color: "#fff", fontSize: 64 }}>        {post?.title ?? "Blog"}      </div>    ),    size,  );}

Unique, readable share images improve click-through from social platforms and chat apps.

Common mistakes

  • Identical titles and descriptions across all dynamic pages.
  • Soft 404s: returning a 200 with a "not found" message instead of calling notFound().
  • Wrong or missing canonicals, especially a localhost metadataBase in production.
  • Sitemap drift: hardcoding URLs so new pages never get listed.
  • Indexing near-duplicates created by filters, tracking parameters or trailing-slash variants.
  • Hidden internal links: navigation built with click handlers instead of real <a>/Link elements.
  • Accessing params outside Suspense with Cache Components enabled, which causes a blocking-route error.

Internal linking

Crawlers discover and weigh pages through links. Link related posts to each other from the article body and from a "related articles" block, put breadcrumbs on every page, and link category and index pages from your main navigation. Use descriptive anchor text, not "click here".

Testing and validation

bash
npm run buildnpm run startcurl -s http://localhost:3000/blog/my-first-post | grep -E "<title>|rel=\"canonical\"|application/ld\+json"curl -sI http://localhost:3000/blog/does-not-exist | head -1   # expect 404curl -s http://localhost:3000/sitemap.xml | head

Then check each page in the Rich Results Test and the URL Inspection tool in Search Console, and compare Core Web Vitals in the field data report after launch.

Best practices

  • Prerender every known route with generateStaticParams.
  • Generate metadata from the same data as the page, with a unique title and description per route.
  • Return real 404s, and 301/308 redirects for moved URLs.
  • Keep one canonical URL per piece of content.
  • Generate the sitemap from the data source and keep lastModified honest.
  • Keep markup valid and content visible without JavaScript.

Conclusion

SEO for dynamic routes comes down to treating each URL as a first-class page: prerendered HTML, an honest status code, specific metadata, a canonical, structured data and a place in the sitemap. Next.js provides each piece as a small, composable API. Wire them to a single data source and your dynamic routes will be as discoverable as static ones.

Frequently asked questions

+−Do dynamic routes hurt SEO in Next.js?

No. Search engines index dynamic routes as long as they return real HTML with unique titles, descriptions and canonical URLs. Prerendering them with generateStaticParams makes them fast and reliably crawlable.

+−What does generateStaticParams do?

It returns the list of parameter values for a dynamic segment so Next.js can prerender those pages at build time instead of rendering them on demand.

+−Why is params a Promise in recent Next.js versions?

Params are request-dependent data, so they are exposed asynchronously. You await them in pages, layouts and generateMetadata. With Cache Components you also wrap the component that reads them in a Suspense boundary.

+−How do I set a canonical URL for a dynamic page?

Return alternates.canonical from generateMetadata, for example alternates: { canonical: `/blog/${slug}` }. Set metadataBase in the root layout so relative URLs resolve to absolute ones.

+−How do I return a real 404 for unknown slugs?

Call notFound() from next/navigation when the data is missing. Next.js renders your not-found UI and sends a 404 status so search engines do not index a soft-404.

+−Should I add FAQ structured data to every page?

No. Google limits FAQ rich results to a narrow set of sites, so only add FAQ markup if it is appropriate and compliant. Article and BreadcrumbList structured data are safer defaults for blog posts.

+−How should I handle pagination and filters for SEO?

Give each indexable page a unique, crawlable URL with its own title and canonical, and avoid indexing endless filter combinations. Link pages with normal anchor elements so crawlers can discover them.

Further reading

  • nextjs.org/docs/app/api-reference/functions/generate-metadata

Hamza Janzaib

Full-Stack Developer based in Karachi, Pakistan. Building web apps, APIs and cloud infrastructure. About me


Related articles

Next.js, React & TypeScriptNovember 28, 202613 min readIntermediate

Managing API Caching and Data Fetching in Next.js

A mental model for Next.js caching layers and a repeatable pattern for fetching, caching and revalidating API data.

Next.js, React & TypeScriptNovember 28, 202613 min readIntermediate

Handling Authentication and Protected Routes in Next.js

Optimistic checks in proxy, real checks next to the data: a layered approach to protecting routes.

Next.js, React & TypeScriptNovember 28, 202612 min readIntermediate

Solving Server and Client Component Problems in Next.js

The errors you will actually hit with Server and Client Components, why they happen and how to fix them.

Built by Hamza Janzaib