Skip to content

Gatsby: Overwrite the default Sitemap index file for additional sitemaps

Published: Updated:

The gatsby-plugin-sitemap package doesn't allow adding additional sitemaps, and the gatsby-plugin-advanced-sitemap package is at the time of writing too buggy for my usage, so I decided to write my own script to overwrite the default sitemap-index.xml file. Here's a quick guide for it!

The functionality is simple: allow the sitemap plugin to do its sitemap generation during the build, and at the end of the build process, replace the sitemap index file with a new one.

Here are the steps for achieving that:

1. Make sure you have gatsby-plugin-sitemap installed and it works.

2. If you don't have a gatsby-node.js file at the root of your project (next to gatsby-config.js), create it.

3. At the end of the gatsby-node.js file, copy-paste this:

1exports.onPostBuild = async () => {
2 // fs is part of Node.js, so let's use it
3 var fs = require('fs');
4
5 // Remove previous sitemap that was generated
6 try { fs.unlinkSync("public/sitemap-index.xml") } catch(err) {console.error(err)}
7
8 // Get current date in the format that sitemaps use
9 let date = new Date().toISOString();
10
11 // Create a new sitemap and write the contents
12 var jsonStream = fs.createWriteStream("public/sitemap-index.xml");
13 jsonStream.once('open', function(fd) {
14 jsonStream.write(
15`<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
16 <sitemap>
17 <loc>https://vaihe.com/sitemap-0.xml</loc>
18 <lastmod>${date}</lastmod>
19 </sitemap>
20 <sitemap>
21 <loc>https://vaihe.com/component-library/sitemap-0.xml</loc>
22 <lastmod>${date}</lastmod>
23 </sitemap>
24</sitemapindex>`)
25 jsonStream.end();
26 });
27}

4. Replace the domain, change the additional sitemap URL, and if you don't want the automatic lastmod value, you can remove the <lastmod> lines.

Done! Now the sitemap should look like this: https://vaihe.com/sitemap-index.xml

Also note that if you're using an older Gatsby version than v5, the sitemap location is wrong, you need to use public/sitemap/sitemap-index.xml.