Skip to main content

Generate Dynamic Sitemap In Nextjs Automatically

· 4 min read
Sivabharathy

A sitemap is an XML file that lists all the important pages of your website, helping search engines like Google index your content more effectively. In Next.js, you can generate a sitemap dynamically using the next-sitemap package. This article will guide you step-by-step on how to set it up.


🚀 Why Do You Need a Sitemap?

A sitemap improves SEO by:

  • Helping search engines discover your pages faster.
  • Improving website ranking by ensuring all pages are indexed.
  • Allowing control over which pages should be crawled (via robots.txt).

1️⃣ Installing next-sitemap

next-sitemap is a popular package that automatically generates a sitemap for your Next.js application.

Run the following command to install it:

npm install next-sitemap

If using Yarn:

yarn add next-sitemap

2️⃣ Creating the Configuration File

Create a next-sitemap.config.js file in the root of your project and define the sitemap settings:

/** @type {import('next-sitemap').IConfig} */
module.exports = {
siteUrl: 'https://yourwebsite.com', // Replace with your actual domain
generateRobotsTxt: true, // Generates robots.txt automatically
sitemapSize: 5000, // Splits sitemap if you have more than 5000 pages
changefreq: 'daily', // How often pages are updated
priority: 0.7, // Default priority for pages
};

Explanation:

  • siteUrl: The base URL of your website.
  • generateRobotsTxt: Automatically generates a robots.txt file.
  • sitemapSize: Defines how many links should be in a single sitemap file before splitting.
  • changefreq: Specifies how often the pages are updated (daily, weekly, etc.).
  • priority: Helps search engines determine the importance of pages.

3️⃣ Updating package.json

Modify the package.json file to add a post-build script that will generate the sitemap after each build:

"scripts": {
"postbuild": "next-sitemap"
}

Why? This ensures that the sitemap is generated automatically when running next build.


4️⃣ Generating the Sitemap

Now, run the following command to build your project and generate the sitemap:

npm run build

This will create the following files inside the public/ folder:

/public/sitemap.xml
/public/robots.txt

Once deployed, visit:


5️⃣ Submitting Your Sitemap to Google

  1. Go to Google Search ConsoleSitemaps.
  2. Enter your sitemap URL (https://yourwebsite.com/sitemap.xml).
  3. Click Submit.
  4. Wait for Google to crawl your site.

📌 Bonus: Generating a Dynamic Sitemap (For Large Apps)

If your app has dynamic routes (e.g., blog posts, user profiles), you may want to generate the sitemap dynamically. You can create an API route for this.

👉 Create /pages/api/sitemap.js

import { SitemapStream, streamToPromise } from 'sitemap';
import { createGzip } from 'zlib';

export default async function handler(req, res) {
res.setHeader('Content-Type', 'application/xml');
res.setHeader('Content-Encoding', 'gzip');

const smStream = new SitemapStream({ hostname: 'https://yourwebsite.com' });
const pipeline = smStream.pipe(createGzip());

// Add static pages
smStream.write({ url: '/', changefreq: 'daily', priority: 1.0 });
smStream.write({ url: '/about', changefreq: 'weekly', priority: 0.8 });

// Fetch and add dynamic pages (e.g., from a database)
const posts = [{ slug: 'post-1' }, { slug: 'post-2' }];
posts.forEach(post => smStream.write({ url: `/blog/${post.slug}`, changefreq: 'weekly', priority: 0.7 }));

smStream.end();
streamToPromise(pipeline).then(sm => res.end(sm));
}

👉 Updating robots.txt to Include Dynamic Sitemap

If you use a dynamic sitemap, add this to robots.txt:

Sitemap: https://yourwebsite.com/api/sitemap

This tells search engines where to find your dynamically generated sitemap.


🎉 Conclusion

Setting up a sitemap in Next.js is simple and boosts your SEO performance. By using next-sitemap, you ensure that search engines can index all your pages automatically. If your app has dynamic content, you can use an API-based sitemap for better control.

Key Takeaways:

  • Install next-sitemap and configure it.
  • Automate sitemap generation using postbuild.
  • For dynamic pages, use an API route to generate sitemaps.
  • Submit your sitemap to Google Search Console.

🚀 Your website is now SEO-ready! Let me know if you have any questions. 😊