Skip to content
PD
All insights

Generating Sitemap in Next.js with App Router

Learn how to generate a dynamic sitemap.xml in Next.js using the App Router. Improve your site's SEO with automated and up-to-date sitemap generation for both static and dynamic pages.

Generating Sitemap in Next.js with App Router

Search engines like Google rely on sitemaps to discover and index your website’s content efficiently. With Next.js App Router, creating a dynamic sitemap.xml is straightforward. In this guide, you’ll learn how to create a sitemap endpoint that includes both static and dynamic routes using the App Router.


Why You Need a Sitemap

  • Improves SEO by helping search engines index your site efficiently.
  • Ensures all your pages, including dynamic content (e.g., blog posts, portfolios), are discoverable.
  • Provides a simple and centralized structure of your site’s URLs.

1. Setup Your API Route

Create the file:

/app/api/sitemap/route.js

2. Install sitemap Library

You’ll use the sitemap package to generate XML.

npm install sitemap

Also import the Readable stream:

import { Readable } from "stream";

3. Create the route.js Handler

Here’s an example that generates XML for both static and dynamic pages:

// app/api/sitemap/route.js

import { NextResponse } from "next/server";
import { SitemapStream, streamToPromise } from "sitemap";
import { Readable } from "stream";

// Example dynamic content fetchers
async function fetchPortfolios() {
  const res = await fetch("https://your-api.com/portfolios");
  if (!res.ok) return [];
  const data = await res.json();
  return data.map((item) => `/portfolio/${item.slug}`);
}

async function fetchArticles() {
  const res = await fetch("https://your-api.com/articles");
  if (!res.ok) return [];
  const data = await res.json();
  return data.map((item) => `/articles/${item.slug}`);
}

export async function GET() {
  const staticPages = [
    "/",
    "/about",
    "/portfolio",
    "/articles",
    "/contact",
  ];

  const [portfolios, articles] = await Promise.all([
    fetchPortfolios(),
    fetchArticles(),
  ]);

  const allPages = [...staticPages, ...portfolios, ...articles];

  const sitemapStream = new SitemapStream({
    hostname: "https://your-domain.com",
  });

  const xml = await streamToPromise(Readable.from(allPages).pipe(sitemapStream));

  return new NextResponse(xml.toString(), {
    status: 200,
    headers: {
      "Content-Type": "application/xml",
    },
  });
}

4. Accessing the Sitemap

Once deployed, your sitemap is available at:

https://your-domain.com/api/sitemap

5. Automate Sitemap Updates

To ensure new content is reflected in the sitemap:

  • Use Incremental Static Regeneration (ISR) or revalidation.
  • Or trigger a rebuild via webhook after new content is added in your CMS.

6. Submit to Google Search Console

https://your-domain.com/api/sitemap

Summary

Generating a sitemap in Next.js using the App Router is efficient and SEO-friendly. You can include any number of static or dynamic pages with full control over the output format. Plus, you’re free to scale and automate sitemap updates as your site grows.

// More insights

Generating Sitemap in Next.js with App Router | Prabhat Dawadi