After I changed my blog over to Next.js, I was looking for a quick and easy way to add a
sitemap.xml
file to my site. And I stumbled across this nifty module that has maybe the lowest effort possible. Here is how I used next-sitemap to quickly add sitemap support.1. Install
or
2. Add Configuration
3. Add to Scripts
I setup the
package.json
to handle running the sitemap module automatically. This uses a nice feature of NPM, where post
will run after the task it prefixes. In this case it will run after npm run build
automatically without any extra work.Output
This writes a
sitemap.xml
and robots.txt
file to the public
folder. The robots file is automatically referencing the sitemap so search engine crawlers can find it.robots.txt
sitemap.xml
How it Works
This works by crawling the output of the
.next
folder after building the site. The output in the folder determines the pages reference in the sitemap. It then creates all assets in the public
folder needed by Google and other search engines. It is a simple approach that relies on the .next
not changing its underlying behavior of it’s output. In other words, simple, but not robust. Alternative Approaches
- One alternative would be to create a
sitemap.xml.js
route that outputs a xml formatted file. This file would have to import all the pages that were used to build the site, and generate the output. This is very similar to what my Svelte/Sapper project did.
- Another approach would be to modify the webpack configuration to gather information about all exported files, and then create a sitemap with that information.
- Finally, another approach would be to create a
/pages/api/sitemap.js
route that outputs xml similar to the first alternative.