How to generate a sitemap for your Next.js website
I have several websites (including this one) that run on Next.js and are hosted on Vercel. Recently I wondered how to generate a sitemap for my websites, and it turned out to be quite easy.
Here's a step-by-step guide.
Sitemap with Next.js
We are going to use the next-sitemap package.
First, let's install it.
npm i -D next-sitemap
Next, we need to create a configuration file, next-sitemap.config.js
like this:
module.exports = {
siteUrl: 'https://www.strictmode.io/',
generateRobotsTxt: true,
}
Here siteUrl
is your website's domain, and generateRobotsTxt
is an optional key to generate the robots.txt file.
Now we can try generating the sitemap using the command:
./node_modules/.bin/next-sitemap
But we can only do that after the build is generated, so it's more convenient to add this script into the postbuild
npm task (in package.json
) (this task will always run after npm run build
).
{
"scripts": {
"dev": "next dev",
"build": "next build",
"postbuild": "next-sitemap",
"start": "next start",
"lint": "next lint"
}
}
Now, if we simply run npm run build
, it should create three new files in the public
directory:
public/robots.txt
public/sitemap-0.xml
public/sitemap.xml
I choose not to check them in into the GIT repository and instead let Vercel
generate them every time on deployment. So I put this into .gitignore
:
public/robots.txt
public/sitemap*
When your website is deployed, you should be able to open the sitemap in a browser using a URL like this https://www.strictmode.io/sitemap.xml (which is a sitemap list), and https://www.strictmode.io/sitemap-0.xml - the actual sitemap.
Congratulations, now you have your sitemap!