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: 'http://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.
We first imported next-connect
to handle requests.
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.
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()
.
Loop over all the posts that you stored in posts
variable. Write the URL with the id or slug, then end by writing sitemap.
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