Back to Blog
Tutorial

The Complete Guide to Sitemaps in Next.js

January 15, 2026 10 min read

Next.js is one of the most popular React frameworks, but sitemap generation can be tricky---especially with the App Router. This guide covers all the approaches for generating sitemaps in Next.js applications.

Option 1: Static Generation with next-sitemap

The most common approach uses the next-sitemap package to generate sitemaps at build time:

npm install next-sitemap
// next-sitemap.config.js
module.exports = {
  siteUrl: 'https://example.com',
  generateRobotsTxt: true,
  sitemapSize: 7000,
}

Add the postbuild script to your package.json:

{
  "scripts": {
    "build": "next build",
    "postbuild": "next-sitemap"
  }
}
This approach works well for small to medium sites but can slow down builds significantly for sites with many pages.

Option 2: App Router Route Handler

With Next.js 13+ App Router, you can create a dynamic sitemap using a route handler:

// app/sitemap.xml/route.ts
import { getAllPosts } from '@/lib/posts';

export async function GET() {
  const posts = await getAllPosts();

  const sitemap = `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <url>
    <loc>https://example.com</loc>
    <lastmod>${new Date().toISOString()}</lastmod>
  </url>
  ${posts.map(post => `
  <url>
    <loc>https://example.com/blog/${post.slug}</loc>
    <lastmod>${post.updatedAt}</lastmod>
  </url>`).join('')}
</urlset>`;

  return new Response(sitemap, {
    headers: {
      'Content-Type': 'application/xml',
    },
  });
}

Option 3: External Hosting with SitemapHost

For larger sites or sites that need frequent updates, external hosting removes sitemap generation from your build process entirely:

// scripts/sync-sitemap.mjs
const response = await fetch('https://dash.sitemaphost.app/api/sitemap/generate', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-API-Key': process.env.SITEMAPHOST_API_KEY,
  },
  body: JSON.stringify({
    domain: 'sitemap.yoursite.com',
    urls: await getAllUrls(),
  }),
});

Which Approach Should You Use?

  • Small sites (<1000 pages): next-sitemap works great, or use our free sitemap generator for a quick one-off sitemap
  • Medium sites (1000-50000 pages): Route handler or external hosting
  • Large sites (>50000 pages): External hosting recommended
SH

SitemapHost Team

Insights on SEO, sitemaps, and web infrastructure.

Ready to simplify your sitemaps?

Start hosting your sitemaps with SitemapHost today.

Get Started Free