@julio
To build a sitemap in Express.js, you can use the sitemap package. Follow these steps:
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();
}
});
|
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.