Programmatic SEO with Next.js: The Complete Tutorial

Step-by-step Next.js App Router tutorial for programmatic SEO: async dynamic routes, generateStaticParams, real 404s, dynamic metadata, sitemaps, and scaling beyond 10k pages.

Updated 6 min read
Programmatic SEO with Next.js: The Complete Tutorial

Most programmatic SEO tutorials stop at a toy loop and leave out the parts that break in production: soft 404s, exploding build times, orphaned URLs, and outdated Next.js code that fails typechecking in Next.js 15 and 16.

This walkthrough builds a working programmatic SEO setup in the Next.js App Router from scratch, using modern async route params, proper HTTP 404 handling, per-page metadata, and a real XML sitemap.

If you want the strategy side first (picking keywords, validating SERPs, and avoiding thin-page penalties), read our programmatic SEO guide before writing code.

Why Next.js fits programmatic SEO

Search engines still prefer fast, complete HTML on the first response. With Next.js App Router you get:

  • Static generation plus on-demand ISR: Pre-render your highest-value pages at build time with generateStaticParams, and generate long-tail pages on demand with Incremental Static Regeneration (ISR) so builds do not take an hour.
  • First-class metadata APIs: Export generateMetadata right beside the page component to output unique title tags, meta descriptions, Open Graph tags, and canonical URLs on the server.
  • Built-in sitemap and robots routes: Write app/sitemap.ts and app/robots.ts in TypeScript instead of maintaining fragile post-build XML scripts.
  • Real React components on every page: You are not stuck with plain text templates. You can embed calculators, filters, charts, or interactive previews on every programmatic URL so the page helps the visitor.
Next.js App Router architecture for programmatic SEO

Step 1: Create the Next.js project

Start a TypeScript App Router project with create-next-app and pass --no-cache-components so route segment exports (dynamicParams and revalidate) work cleanly in Next.js 16:

npx create-next-app@latest my-pseo-site --typescript --app --eslint --no-cache-components
cd my-pseo-site
npm run dev

Confirm the dev server loads at http://localhost:3000. The default tsconfig.json maps @/* to your project root (or src/* if you chose the src folder), which keeps data imports clean.

Step 2: Prepare a structured dataset

Structuring a dataset for programmatic SEO pages

For a minimal working example, we will build city population pages from a small sample JSON file. In production, swap this loader for PostgreSQL, SQLite, or a build-time fetch from your CMS or API.

Create data/cities.json in the project root (or src/data/cities.json if you enabled the src folder during setup, so @/data/cities.json resolves cleanly), using sample figures and an example update date:

[
  {
    "city": "New York",
    "state": "NY",
    "population": 8419000,
    "slug": "new-york",
    "updatedAt": "2026-01-15"
  },
  {
    "city": "Los Angeles",
    "state": "CA",
    "population": 3971000,
    "slug": "los-angeles",
    "updatedAt": "2026-01-15"
  },
  {
    "city": "Chicago",
    "state": "IL",
    "population": 2746000,
    "slug": "chicago",
    "updatedAt": "2026-01-15"
  }
]

Notice two fields that matter later: a clean lowercase slug for URLs, and a real updatedAt date from your dataset so your sitemap does not stamp every page with today's timestamp on every deploy.

Add a small shared data helper in lib/cities.ts:

import citiesData from '@/data/cities.json'
 
export interface City {
  city: string
  state: string
  population: number
  slug: string
  updatedAt: string
}
 
const cities: City[] = citiesData
 
export function getAllCities(): City[] {
  return cities
}
 
export function getCityBySlug(slug: string): City | undefined {
  return cities.find((item) => item.slug === slug)
}

Step 3: Build the dynamic page template (Next.js 15 and 16 App Router)

Create app/city/[slug]/page.tsx. In Next.js 15 and 16, params is a Promise and must be awaited in both generateMetadata and the page component.

import type { Metadata } from 'next'
import Link from 'next/link'
import { notFound } from 'next/navigation'
import { getAllCities, getCityBySlug } from '@/lib/cities'
 
export const dynamicParams = false
 
interface PageProps {
  params: Promise<{ slug: string }>
}
 
export async function generateStaticParams() {
  return getAllCities().map((city) => ({
    slug: city.slug,
  }))
}
 
export async function generateMetadata({ params }: PageProps): Promise<Metadata> {
  const { slug } = await params
  const city = getCityBySlug(slug)
 
  if (!city) {
    return {}
  }
 
  return {
    title: `${city.city}, ${city.state} Population and Key Facts`,
    description: `Population overview (${city.population.toLocaleString()}) and demographic facts for ${city.city}, ${city.state}.`,
    alternates: {
      canonical: `https://example.com/city/${city.slug}`,
    },
  }
}
 
export default async function CityPage({ params }: PageProps) {
  const { slug } = await params
  const city = getCityBySlug(slug)
 
  if (!city) {
    notFound()
  }
 
  const nearby = getAllCities().filter((item) => item.slug !== city.slug)
 
  return (
    <main>
      <h1>
        {city.city}, {city.state}
      </h1>
      <p>Population: {city.population.toLocaleString()}</p>
 
      <section>
        <h2>Compare other cities</h2>
        <ul>
          {nearby.map((item) => (
            <li key={item.slug}>
              <Link href={`/city/${item.slug}`}>
                {item.city}, {item.state}
              </Link>
            </li>
          ))}
        </ul>
      </section>
    </main>
  )
}

Look closely at three details here that save painful SEO bugs later:

  • notFound() instead of a custom error div: Returning <div>City not found</div> sends HTTP 200 to Googlebot. Search Console flags those as soft 404s and wastes crawl budget. Calling notFound() returns a real HTTP 404 status.
  • export const dynamicParams = false: When your entire dataset is pre-built at deploy time (say 50 to 3,000 pages), setting this to false makes unknown slugs 404 immediately without hitting your database or rendering on demand.
  • Related internal links: Every programmatic page should link to a handful of sibling pages and back up to its category or directory page. Orphaned pages that only exist in your XML sitemap get crawled slowly or dropped from the index.

Step 4: Add an HTML index page

Do not rely on your XML sitemap alone to get pages discovered. Create app/city/page.tsx that links out to your city pages (with pagination or A-Z grouping once you pass a few hundred rows):

import Link from 'next/link'
import { getAllCities } from '@/lib/cities'
 
export default function CitiesIndexPage() {
  const cities = getAllCities()
 
  return (
    <main>
      <h1>All Cities</h1>
      <ul>
        {cities.map((city) => (
          <li key={city.slug}>
            <Link href={`/city/${city.slug}`}>
              {city.city}, {city.state}
            </Link>
          </li>
        ))}
      </ul>
    </main>
  )
}

A stable HTML index page gives Googlebot a single reliable crawl path to reach every template URL. Avoid shuffling or randomly rotating which links appear on your index page, because changing links on every crawl looks like deleted pages to crawlers.

Step 5: Generate sitemap.xml with app/sitemap.ts

Next.js serves an XML sitemap automatically at /sitemap.xml when you export a default function returning MetadataRoute.Sitemap from app/sitemap.ts:

import type { MetadataRoute } from 'next'
import { getAllCities } from '@/lib/cities'
 
const BASE_URL = 'https://example.com'
 
export default function sitemap(): MetadataRoute.Sitemap {
  const cityRoutes: MetadataRoute.Sitemap = getAllCities().map((city) => ({
    url: `${BASE_URL}/city/${city.slug}`,
    lastModified: new Date(city.updatedAt),
  }))
 
  return [
    {
      url: BASE_URL,
      lastModified: new Date('2026-01-15'),
    },
    {
      url: `${BASE_URL}/city`,
      lastModified: new Date('2026-01-15'),
    },
    ...cityRoutes,
  ]
}

Two practical notes on sitemaps:

  • Skip changeFrequency and priority if you want cleaner XML. Google has stated for years that it ignores both tags; accurate lastModified dates matter far more.
  • Splitting past 50,000 URLs in Next.js 16: Standard sitemaps cap out at 50,000 URLs or 50 MB uncompressed. You can export generateSitemaps() alongside sitemap(props: { id: Promise<string> }) in app/sitemap.ts to shard your URLs into /sitemap/0.xml, /sitemap/1.xml, and so on. In Next.js 16, props.id is a Promise<string>, so parse it with const id = Number(await props.id) before slicing your dataset. Also note that adding generateSitemaps() stops Next.js from serving /sitemap.xml (it returns 404), so list every shard URL in app/robots.ts and submit each shard in Search Console (or add a dedicated sitemap index route).

For a single-sitemap site, add app/robots.ts pointing crawlers straight to your sitemap URL (if you shard with generateSitemaps(), pass an array of shard URLs to sitemap instead):

import type { MetadataRoute } from 'next'
 
export default function robots(): MetadataRoute.Robots {
  return {
    rules: {
      userAgent: '*',
      allow: '/',
    },
    sitemap: 'https://example.com/sitemap.xml',
  }
}

Scaling past 5,000 pages without breaking builds

Pre-rendering 500 or 2,000 pages in generateStaticParams finishes in seconds. Pre-rendering 50,000 pages on every Git push will time out your CI runner and burn database connections.

Once your dataset grows large, switch to hybrid ISR (keeping --no-cache-components so dynamicParams and revalidate remain valid):

  1. Return only your top 500 to 1,000 highest-traffic slugs from generateStaticParams.
  2. Set export const dynamicParams = true and export const revalidate = 86400 (24 hours) so long-tail pages generate on the first request and stay cached at the edge or server.
  3. Noindex thin rows until they have real data. If a database row is missing half its fields, return robots: { index: false, follow: true } from generateMetadata instead of publishing an empty shell.

Deploying to production

You can deploy this setup on Vercel, Cloudflare Workers, or a Docker container on your own VPS. Before submitting your sitemap (/sitemap.xml, or your /sitemap/0.xml shards if split) in Google Search Console, check three things on your live URL:

  • View page source (curl -s https://yourdomain.com/city/new-york) and confirm the <h1>, body data, <title>, and <link rel="canonical"> exist in the raw HTML response.
  • Request a fake slug (/city/does-not-exist) and verify the server returns HTTP 404, not 200.
  • Test one URL in Search Console's URL Inspection live test to see what Googlebot renders.

Next steps

This starter gives you the clean Next.js plumbing. Once the routes work, the main job in programmatic SEO is picking a dataset with genuine search demand, designing a template that beats the current top ten results, and monitoring indexing as you ship in batches.

If you want the full playbook, production Next.js boilerplate, and real teardowns of sites we have scaled, check out the full course:

👉 Get the Programmatic SEO Course

Ilias Ism

Written by

Ilias Ism

Ilias is the co-founder of MagicSpace SEO, helping small businesses grow with SEO. With a decade of experience as a CTO and marketer, he offers SEO consulting and SEO services to clients worldwide.

  • Co-founder of MagicSpace SEO & founder of LinkDR
  • 100+ recorded SaaS SEO audits on SEO Roast
  • Author of Blitz SEO & open-source seo-skills

MagicSpace SEO, Zug, Switzerland

SEO audits, monthly plans and link building for software companies

Run by the founders, Ilias Ism and Sasha. Rated 5.0 on Clutch.

15-min live audit

Or get a recorded SEO audit • Both include next steps and an intro to our services

MagicSpace Team - Ilias & Sasha

Keep reading

How to Extract Text From Video: 5 Methods Compared (2026)
Tools6 min read

How to Extract Text From Video: 5 Methods Compared (2026)

How to extract text from video: spoken words and on-screen text need different tools. Five methods compared, with prices and where each one falls short.

SEO5 min read

Content Distribution Guide: Turn 1 Article Into 7X the Reach

Everyone writes blog posts, almost nobody distributes them. Turn one article into a Twitter thread, LinkedIn post, Pinterest pins, Reddit answer, Medium syndication, newsletter and Quora response: same content, 7x the reach.