Save time by Generating Sitemaps Dynamically in NextJS by@mindasoft

Save time by Generating Sitemaps Dynamically in NextJS

Mindasoft HackerNoon profile picture


App development company

In this post, you will generate your own Next js sitemap in under 1 minute.

First, you will need to install a sitemap package to do this action.

Open up your terminal and run:

npm install sitemap

In this tutorial, I have used next-connect to handle my requests. If you are already using it you can follow this blog without doing anything extra. If you don’t have next-connect open up your terminal and run:

npm install next-connect

After you install these packages we need a sitemap.js file in the API folder.


It’s time to generate our sitemap. Copy this code into sitemap.js and edit your website section.

import nc from 'next-connect';
import Blog from '../../models/blog';
import dbConnect from '../../utils/db'
const handler = nc();

handler.get(async (req, res) => {

// connect to database (prepare it in utils folder if you dont have it)
await dbConnect()

// Get the all Blog posts 
const posts = await Blog.find().lean()

const { createWriteStream } = require('fs');
const { SitemapStream } = require('sitemap');
const sitemap = new SitemapStream({ hostname: '' });
const writeStream = createWriteStream('./public/sitemap.xml');

// Writing static pages to sitemap
sitemap.write({ url: '/', changefreq: 'daily', priority: 1 })
sitemap.write({ url: '/staticpage/', changefreq: 'daily', priority: 0.8 })
sitemap.write({ url: '/staticpage1/', changefreq: 'daily', priority: 0.8 })
sitemap.write({ url: '/staticpage2/', changefreq: 'daily', priority: 0.8 })
// Writing Dynamic Pages to sitemap
// iterate over all posts coming from Mongo DB Blog model => {
sitemap.write({ url: `/myblog/${}/`, changefreq: 'daily', priority: 0.9 })

// Finish writing sitemap

// Send a message after process done
res.status(200).json({message: "Done"})})
export default handler

Now let me explain all this code.

  1. We first imported next-connect to handle requests.

  2. Then we imported the Blog model that we prepared before to get all posts. You can fetch all your posts through an API endpoint instead of using the Blog model.

  3. After that, we connected to the database to store all posts in the posts variable. Now we can start writing our static pages with sitemap.write().

  4. Loop over all the posts that you stored in posts variable. Write the URL with the id or slug, then end by writing sitemap.

  5. Visit your localhost:3000/api/sitemap in development mode and you will see that sitemap.xml is generated in your public folder.

Also Published here


Signup or Login to Join the Discussion


Related Stories