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:
express
and sitemap
modules.Sitemap
class from the sitemap
module, with the configuration options such as the hostname, cache time, and initial URLs.toXML
method of the sitemap instance and send it as the response.application/xml
.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.
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
Asked: 2022-10-07 11:00:00 +0000
Seen: 14 times
Last updated: Jan 13 '23
How can you create an OpenGL plot without relying on external libraries, starting from scratch?
How can I use iText7 to create a PDF that includes a pie chart?
How can I create a monitor in Datadog that includes multiple resources' metrics in one monitor?
Create a regular expression for the following format.
How to create GS1-128 using ZXing.Net?
Is it advisable to create event handlers in a separate method rather than inline all the time?
How to implement a leaderboard in Flutter?
How to create a plot using mplfinance and PyQt5 that includes a volume graph?