Generate a Sitemap in Next.js

Posted in Programming

Generating a sitemap will improve your site's search results, one of the necessary steps for Search Engine Optimization (SEO). This article describes one way to accomplish this in Next.js.

Install the Next.js sitemap plugin:

npm install next-sitemap

Then follow the instructions for using the package .

My site lists blog posts under /blog, but also under /blog/category/{category}. I don't want to dilute Google search results with the same content at different paths, so I exclude everything in /blog/category/* from my sitemap. Here's my next-sitemap.config.js file:

const Config = require('./lib/config');
const siteUrl = Config.url;
module.exports = {
generateRobotsTxt: true,
robotsTxtOptions: {
policies: [
{userAgent: "*", disallow: "/blog/category/*"},
{userAgent: "*", allow: "/"},
exclude: ["/blog/category/*"]

It's also important to exclude robots.txt and all the sitemap XML files from Git since it's generated every time you build. I added this to my .gitignore:


Delete public/robots.txt and public/sitemap*.xml, then run the build manually:

rm -f public/robots.txt public/sitemap*.xml
npm run build

Verify that public/robots.txt, public/sitemap.xml, etc... are created and look correct.

Add a postbuild property to your package.json file to automatically generate the sitemap whenever you build the app.

"scripts": {
"dev": "next dev",
"build": "next build",
"postbuild": "next-sitemap",
"start": "next start",
"lint": "next lint"

That's all there is to it. Hope this helps.

- E