Sling Academy
Home/Node.js/Node.js + Express: How to create an XML sitemap

Node.js + Express: How to create an XML sitemap

Last updated: December 30, 2023

Creating an XML sitemap for your website is crucial for SEO. This guide will demonstrate how to generate a dynamic XML sitemap using Node.js and Express with modern JavaScript syntax.

Initial Setup

Project Structure

Initial directory structure including package dependencies and initial server setup.

project/
|-- node_modules/
|-- public/
|-- views/
|-- app.js
`-- package.json

Installing Dependencies

We’ll need the ‘express’ and ‘sitemap’ packages. Install them using npm:

npm install express sitemap

Creating a Basic Sitemap

Setting Up Express

Basic Express server setup with a route for the sitemap.

import express from 'express';

const app = express();

app.get('/sitemap.xml', function(req, res) {
 // Sitemap generation logic will go here
});

app.listen(3000, () => {
 console.log('Server running on port 3000');
});

Using ‘sitemap’ Package

Generate a sitemap using the ‘sitemap’ library.

import { SitemapStream, streamToPromise } from 'sitemap';

// ...previous code

app.get('/sitemap.xml', function(req, res) {
 const sitemap = new SitemapStream({ hostname: 'https://example.com' });

 sitemap.write({ url: '/', changefreq: 'daily', priority: 0.7 });
 // Add more URLs to the sitemap as needed
 sitemap.end();

 streamToPromise(sitemap).then(sitemapOutput => {
 res.header('Content-Type', 'application/xml');
 res.send(sitemapOutput.toString());
 });
});

Advanced Sitemap Features

Dynamic Sitemap Generation

Fetching URLs from a database or API and dynamically adding them to the sitemap.

// Assume we have an async function fetchUrlsFromDB() that returns a list of URLs

// ...previous code

app.get('/sitemap.xml', async function(req, res) {
 const sitemap = new SitemapStream({ hostname: 'https://example.com' });
 const urls = await fetchUrlsFromDB();

 urls.forEach(url => {
 sitemap.write({ url });
 });
 sitemap.end();

 const sitemapOutput = await streamToPromise(sitemap);
 res.header('Content-Type', 'application/xml');
 res.send(sitemapOutput.toString());
});

Automated Sitemap Updates

Automating sitemap updates on a scheduled basis using cron jobs or similar schedulers.

// Install node-cron package

// ...previous code

// Set up a cron job
import cron from 'node-cron';

cron.schedule('0 0 * * *', function() {
 // Fetch URLs and regenerate sitemap.
});

Conclusion

This tutorial outlined the process of creating an extensible XML sitemap generator with Node.js and Express. By using modern JavaScript features and the ‘sitemap’ library, we can boost a site’s SEO with a well-structured sitemap.

Next Article: Node.js + Express: How to Return PDF Files

Previous Article: Node + Express + Mongoose: CRUD example (Rest API)

Series: Node.js & Express Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates