Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

There are different ways to create a sitemap using ExpressJS but one common approach is to use a middleware that generates the sitemap XML file and returns it in the response.

Here's an example of how to create a sitemap middleware in ExpressJS:

const express = require('express');
const sm = require('sitemap');

const app = express();

const sitemap = sm.createSitemap({
  hostname: 'https://example.com',
  cacheTime: 600000, // 600 sec - cache purge period
  urls: [
    { url: '/', changefreq: 'monthly', priority: 0.8 },
    { url: '/about', changefreq: 'monthly', priority: 0.7 },
    // add more URLs here...
  ]
});

app.get('/sitemap.xml', (req, res) => {
  sitemap.toXML((err, xml) => {
    if (err) {
      return res.status(500).end();
    }
    res.header('Content-Type', 'application/xml');
    res.send(xml);
  });
});

// add more routes and middleware here...

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

Explanation:

  • We first import the express and sitemap modules.
  • We create an instance of the Sitemap class from the sitemap module, with the configuration options such as the hostname, cache time, and initial URLs.
  • We define a route for the sitemap XML file, which will generate the XML using the toXML method of the sitemap instance and send it as the response.
  • We set the content type header of the response to application/xml.
  • We start the Express app with the listen method.

To add more URLs to the sitemap, we can use the add method of the sitemap instance:

sitemap.add({ url: '/blog', changefreq: 'weekly', priority: 0.6 });

By default, the sitemap middleware will include only the URLs that have a 200 status code. If you want to include URLs with other status codes, use the unfiltered option when creating the sitemap instance:

const sitemap = sm.createSitemap({
  hostname: 'https://example.com',
  cacheTime: 600000,
  urls: [
    //...
  ],
  unfiltered: true,
});

Note that you should update the sitemap periodically (e.g., weekly or monthly) to reflect the changes in your site's content and structure. You can automate this using a task scheduler or a CI/CD pipeline.