Ask Your Question
1

What is the method to create a sitemap using expressjs?

asked 2022-10-07 11:00:00 +0000

nofretete gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-01-13 20:00:00 +0000

lalupa gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-10-07 11:00:00 +0000

Seen: 14 times

Last updated: Jan 13 '23