How to create dynamic sitemap for SEO
Contents
Intro
A sitemap.xml is an XML file that lists all the URLs on your website, guiding search engine crawlers through your content. This file is essential for SEO because it helps search engines index your pages more efficiently. But in dynamic websites where content changes frequently, maintaining a static sitemap can be tedious.
Creating a dynamic sitemap.xml
via an API endpoint that queries the database and builds the sitemap on the fly can be a powerful approach:
Advantages | Disadvantages |
---|---|
✅ Always Up-to-Date | ❌ Performance Concerns |
✅ Reduced Manual Work | ❌ Load on Database |
✅ Scalable Solution | ❌ Complexity |
✅ Flexibility in Data Inclusion | ❌ SEO Impact If Slow or Unavailable |
I'll leave you to decide whether you need this or not. But let's assume you do, and you already have a Node server with an array of entities (from your database) that you want to include in a dynamic sitemap.xml
Setup
I'll explain the main points, using this array of posts as an example:
First, we need to install the XML builder and optionally dayjs (see the spoilers below for functions like getPriority and getChangeFreq)
Build
Here's a simple method that creates a sitemap
constant, then pushes each post as a new URL element into the file. Afterward, we'll respond to the client with the generated file.
Here is a couple interesting points..
Priority
This method calculates a priority score for a given URL based on it's depth (position within the website structure) and update frequency.
Feel free to tune it 😉
Change Frequency
This method determines the change frequency for a given URL based on its last modification date.
Feel free to tune it 😉
Merge
Our final sitemap.xml
file:
Did you know that you can split sitemaps and have as many as you'd like? You can use your main sitemap.xml
as an index file and add references to other parts of your site.
One of these could be your new endpoint, which will use the code I shared with you above: