How to automate a sitemap for Nextjs 12

Web Dev

Fri Dec 30 2022

You may have seen another post on Develop Right where a blog post was written about nextjs-sitemap-generator package which automates sitemap creation for NextJS applications. Unfortunately, this package is now marked as deprecated but luckily another package next-sitemap has came along to replace it.

You can find the existing post here



If you are wanting to quickly switch out the deprecated package or implement the new package for sitemap creation then this thread will quickly be able to get you started. By the end of this thread you will be automatic sitemap creation for static nextjs applications. 


Creating The Config

You need to create the config which the "next-sitemap" package will look for, in this config you will be able to customise the package to do the things you need based on your use case. However this blog we will just focus on the basics but feel free to check the docs here

Create a file name "next-sitemap.config.js", this will contain the config

// next-sitemap.config.js

const config = {
  siteUrl: "",
  generateRobotsTxt: true, // (optional)
  excude: ['/images/*']
  // ...other options

module.exports = config;

As you can see the config includes the following fields:

  • siteUrl - the base domain of your application, url you're serving from and the base domain you want all the links found to reference
  • generateRobotsTxt - optional, if you want a robots.txt file to be created for and linked
  • exclude - optional, if you want to exclude certain directories from being picked up. I did this as images can be found by the package


Run the package

Now that the initial config has been created, you can run the package which will look at the config and generate the sitemap. Ensure you run "next build" before running the package.

To run the package either run "next-sitemap" or "./node_modules/.bin/next-sitemap" based on how you have installed the package, a better way would be to add "next-sitemap" to the package.jsons script section, such as "generate:sitemap" for example. 

// package.json
"generate:sitemap": "next-sitemap",


Run the command and check the output, by default the sitemap will be generated inside of the public folder. 

Double check the output, ensure the files are what you expect


Config the Package to Your Needs

You can find additional config based on your requirements at next-sitemap