Adding sitemap in Next.js

How to improve SEO by adding sitemap to SSR or SSG Next.js website

To add a sitemap to a dynamic or statically generated website, we can use the following package:

https://www.npmjs.com/package/next-sitemap

To install this:

npm i -D next-sitemap

It requires a file called next-sitemap.config.js to be added to the project root.

/** @type {import('next-sitemap').IConfig} */
const config = {
  siteUrl: 'https://jsbisht.in',
  generateRobotsTxt: true,
  outDir: 'out'
}

module.exports = config

NOTE: If you are gonna use it for your dynamic website (which by default will be using 'public' folder), you can either skip the outDir as it defaults to public or specify one.

Now add it to your package.json as follows:

{
  "scripts": {
    "dev": "next dev",
    "build": "next build && next export",
    "sitemap": "next-sitemap"
  }
}

Now run the command:

npm run sitemap

It would produce:

out
 |---> robots.txt
 |---> sitemap.xml
 |---> sitemap-0.xml