DEV Community

Cover image for How to Generate a Dynamic Sitemap in Next.js ?
swhabitation
swhabitation

Posted on • Originally published at swhabitation.com

3

How to Generate a Dynamic Sitemap in Next.js ?

A sitemap is so necessary for SEO because it helps search engines like Google crawl and index your pages easily. If you have a Next.js site with dynamically generated content (e.g., blog posts, product pages, or user profiles), you need a dynamic sitemap that updates automatically when new pages are added.

In this blog, we’ll learn:

  • Why sitemaps matter for SEO ?
  • How to generate a dynamic sitemap in Next.js ?
  • How to automatically update it when content changes ?

At the end, your Next.js site will have a fully functional sitemap that keeps search engines happy go lucky and boosts your rankings on next level.

Why Do You Need a Dynamic Sitemap in Next.js ?

A sitemap.xml file tells Google which pages exist on your website. It’s especially useful when:

Image description

  • You have a big website with multiple pages.
  • Your site updates frequently, like a blog or e-commerce store.
  • You want to improve SEO and indexing speed.

Instead of manually updating a sitemap every time you publish a new page, we’ll generate it dynamically in Next.js so it always stays up to date!

Step 1: Create a Dynamic API Route for Sitemap,

In Next.js, we can create a dynamic sitemap using an API route that fetches URLs from a database or CMS.

  1. Inside the pages/api/ folder, create a new file:
    => pages/api/sitemap.xml.js

  2. Add this below code-snippet to generate the sitemap:

import { getAllPages } from "../../lib/api"; // Fetch pages dynamically

export default async function handler(req, res) {
  const pages = await getAllPages(); // Fetch dynamic URLs

  const baseUrl = "https://yourwebsite.com"; // Change this to your actual domain

  const sitemap = `<?xml version="1.0" encoding="UTF-8"?>
  <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <url>
      <loc>${baseUrl}</loc>
      <priority>1.0</priority>
    </url>
    ${pages
      .map(
        (page) => `
    <url>
      <loc>${baseUrl}/${page.slug}</loc>
      <lastmod>${new Date(page.updatedAt).toISOString()}</lastmod>
      <priority>0.8</priority>
    </url>`
      )
      .join("")}
  </urlset>`;

  res.setHeader("Content-Type", "application/xml");
  res.status(200).send(sitemap);
}
Enter fullscreen mode Exit fullscreen mode

What This Code Does ?

=> Fetches dynamic pages from getAllPages().

=> Generates an XML sitemap dynamically.

=> Sends it as a response when /api/sitemap.xml is requested.

Step 2: Make Sitemap Available at /sitemap.xml

Now, let’s make sure Google can access it. so, open next.config.js and add below code snippet,

module.exports = {
  async rewrites() {
    return [
      {
        source: "/sitemap.xml",
        destination: "/api/sitemap.xml",
      },
    ];
  },
};
Enter fullscreen mode Exit fullscreen mode

When you visit example.com/sitemap.xml, it will serve the dynamically generated sitemap!

Step 3: Submit Your Sitemap to Google Search Console

Google will now automatically crawl and index your pages whenever they update.

Bonus: Automatically Rebuild Sitemap on Content Changes

If your content updates frequently, you can revalidate the sitemap automatically using Next.js Incremental Static Regeneration (ISR).

Modify your API route (sitemap.xml.js) like below:

export default async function handler(req, res) {
  res.setHeader("Cache-Control", "s-maxage=86400, stale-while-revalidate"); // Revalidate every 24 hours
  ...
}
Enter fullscreen mode Exit fullscreen mode

This ensures that Google always gets the latest version of your sitemap!

Conclusion

✅ A sitemap.xml is very for SEO.

✅ You can generate it dynamically in Next.js using an API route.

✅ Google will always have updated pages indexed automatically.

With this above mentioned setup, your website’s SEO will improve, and your new pages will get discovered faster.

Hot sauce if you're wrong - web dev trivia for staff engineers

Hot sauce if you're wrong · web dev trivia for staff engineers (Chris vs Jeremy, Leet Heat S1.E4)

  • Shipping Fast: Test your knowledge of deployment strategies and techniques
  • Authentication: Prove you know your OAuth from your JWT
  • CSS: Demonstrate your styling expertise under pressure
  • Acronyms: Decode the alphabet soup of web development
  • Accessibility: Show your commitment to building for everyone

Contestants must answer rapid-fire questions across the full stack of modern web development. Get it right, earn points. Get it wrong? The spice level goes up!

Watch Video 🌶️🔥

Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

DEV shines when you're signed in, unlocking a customized experience with features like dark mode!

Okay