Generate a sitemap for your static NextJS website, hosted on Netlify

If you’ve read my story on using NextJS as a static site on Netlify, you’ve come across the generating of pages as exportPathMap in the next.config.js file. I’ve decided to take that functionality one step further by using that list as input to generate a sitemap.xml file for better SEO performance.

I’ve created a script that reads the list of pages and generates the sitemap standard as an XML file and directly write it to the /static folder. (That last bit ties neatly in with the copying of the _redirects file from my previous article). The script is available in this gist, and I’ll explain the setup here.

I start by reading the exportPathMap from the next.config.js file. It is exposed after all:

I then map over the object that is provided and basically generate an XML node as entry for every item in the object:

There’s some stuff going on for formatting the right date, URL etc. That’s pretty straightforward. I decided to base the priority on the levels of the URL path, so I use a short function to subtract .10 for every level. This seems to, more or less, match how online generators interpret my website. So I’m pretty pleased with it so far:

I then proceed to write the generated XML to the a folder that is publicly accessible after deployment on Netlify:

Bear in mind that you need to have added some sort of post build script to your process. My package.json has a postexport script, which I trigger from my Netlify build command:

The contents of the post-export.js file are the following (including the copying of _redirects):

The Netlify deployment process kicks in after the build command has been completed and it deploys from of the ‘./out’ folder, which makes the sitemap available on your domain from the /static/sitemap.xml path. Now simply provide that URL to, say, Google Search Console and you’re set!

If you’ve set up your CMS to use hooks to trigger a deployment, the sitemap gets updated automatically! 👌

--

--

Dad with ♡ for web, tech, science, tinkering with stuff & photography. Works as an Interaction Developer. Tweets stuff @joranquinten & writes every now and then

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Joran Quinten

Dad with ♡ for web, tech, science, tinkering with stuff & photography. Works as an Interaction Developer. Tweets stuff @joranquinten & writes every now and then