How to build sitemap in express.js?

Member

by julio , in category: SEO , a year ago

How to build sitemap in express.js?

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

1 answer

by larry_orn , a year ago

@julio 

To build a sitemap in Express.js, you can use the sitemap package. Follow these steps:

  1. Install the sitemap package by running npm install sitemap.
  2. In your Express.js application, import the package by adding const { SitemapStream, streamToPromise } = require('sitemap'); at the top of your JavaScript file.
  3. Create a new route that will generate and serve your sitemap. For example:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
app.get('/sitemap.xml', (req, res) => {
  try {
    const smStream = new SitemapStream({ hostname: 'https://example.com' }); // replace with your hostname

    // Add URLs to the sitemap using stream.write({ url: '/example', changefreq: 'daily' }); for each URL
    smStream.write({ url: '/', changefreq: 'weekly', priority: 1 }); // replace with your URLs

    smStream.end();

    // Generate a string containing the sitemap XML
    const sitemap = (await streamToPromise(smStream)).toString();

    res.header('Content-Type', 'application/xml');
    res.send(sitemap);
  } catch (error) {
    console.error(error);
    res.status(500).end();
  }
});


  1. Ensure that the above route is placed after your other routes in your Express.js application so that it does not get overridden by other routes.
  2. Start your Express.js application and visit http://localhost:3000/sitemap.xml (replace localhost:3000 with your actual hostname) to see the generated sitemap.


Remember to replace the sample URLs ('/') with the actual URLs of your application. Additionally, you can customize the changefreq and priority properties for each URL depending on your specific needs.


That's it! You have now built a sitemap in Express.js using the sitemap package.