How to setup a dynamic sitemap.xml file on Netlify
I recently migrated my site to use Remix hosted on Netlify. I wanted to setup a dynamic sitemap.xml file using Netlify functions. Remix already runs on a Netlify function, so I just created a separate function for returning the sitemap. Here’s how I did it.
Create a new sitemap folder in your netlify/functions directory with an index.ts file inside that directory.
Inside your new netlify/functions/sitemap/index.ts file, create a new handler that returns a basic XML file with no content.
To test this out, let’s add a redirect from sitemap.xml to our newly created function. We can add it as a new redirect in the netlify.toml file. You can read more about file based configuration with Netlify here.
Start up netlify dev and make a request to localhost:<YOUR PORT>/sitemap.xml.
You should see a basic XML file returned:
Add your URLs to the sitemap.xml file dynamically using Javascript.
First, we define our site’s URLs in an array with both the URL and the last modified date. These are the only properties I care about on my site, but you can feel free to add any additional fields you want from the XML sitemap specification.
After we’ve created our list of URLs, we can add it to our xmlContent array by mapping each URL into an XML string.
Wrapping up
Make sure you add all your URLs into the URL list and keep it updated as you add additional URLs/update existing pages. This will ensure your pages gets indexed correctly by search engines.