How to Create an Automated Sitemap With Node.js
Join the DZone community and get the full member experience.Join For Free
Site maps are a very important aspect of SEO optimization. Google and other search engines can use a sitemap to figure out where all your pages are and how they link together. In this tutorial, we will be creating an automated site map with Node.JS and Express.
I will be using MongoDB as the database tool, but if you use MySQL or something else, you can easily swap these components out.
Most sites are split into two vague categories:
- Pages that have URLs created (i.e. articles, blog posts, etc).
- Pages that have URLs that rarely change (i.e. home pages, etc).
1. Install Components
First of all, we have to install all the components we need to accomplish this. Below is the skeleton of our index.js file:
The two main components we need for this demo are Express, Mongoose, and sitemap. As mentioned, I am using MongoDB, so mongoose is relevant here. For others, you might have to use different packages. All of these can be installed with the commands below:
2. Get Your Database Contents
Before we begin, let's get our database contents. With MongoDB and mongoose, I can do the following to get my database contents:
Now we have an array of all our data which refers to different articles and categories, all of which have a URL. Next, let's map all that data to a simple array of URLs:
3. Combine With Sitemap
Now let's write all of those URLs to our sitemap. We write each article and category URL to a stream, which is then published to whoever is viewing the sitemap. The final code for our sitemap.xml route looks like this:
Notice that in our
forEach loop for we mention the change frequency and priority:
- A higher priority means that these pages are more important relevant to your site. You should give your most important pages a higher priority.
- Change frequency does not necessarily mean search engines will only crawl pages at that frequency, but it is an indication.
4. Add Any Other Pages
If you want to add other pages not found in your database, just add another
smStream.write line. For example:
5. Index it on Google
Great! Now you have a sitemap, and it's live. I would recommend you use Google's Search Console to ensure the sitemap is registered for your domain, under the 'Site Map' section.
Don't forget to update your robots.txt file with a link to your sitemap as well!
With these simple steps, you've just improved your SEO game ever so slightly.
Published at DZone with permission of Johnny Simpson, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.