paint-brush
Save time by Generating Sitemaps Dynamically in NextJSby@mindasoft
106 reads

Save time by Generating Sitemaps Dynamically in NextJS

by MindasoftMarch 26th, 2022
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

In this post, you will generate your own Next js sitemap in under 1 minute. In this tutorial, I have used next-connect to handle requests. You can fetch all your posts through an API endpoint instead of using the Blog model. Visit your website for development in development mode and you will see that `sitemap.xml` is generated in your public folder. Copy this code into satemap.js and edit your website section to edit your section. Use the sitemaps-next-connect package to create a sitemapp.js file in the api folder.

Company Mentioned

Mention Thumbnail
featured image - Save time by Generating Sitemaps Dynamically in NextJS
Mindasoft HackerNoon profile picture


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: 'https://www.yourwebsite.com' });
const writeStream = createWriteStream('./public/sitemap.xml');
sitemap.pipe(writeStream);

// 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 
posts.map(item => {
sitemap.write({ url: `/myblog/${item.id}/`, changefreq: 'daily', priority: 0.9 })
})

// Finish writing sitemap
sitemap.end();

// 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