Creating an XML sitemap for your website is crucial for SEO. This guide will demonstrate how to generate a dynamic XML sitemap using Node.js and Express with modern JavaScript syntax.
Initial Setup
Project Structure
Initial directory structure including package dependencies and initial server setup.
project/
|-- node_modules/
|-- public/
|-- views/
|-- app.js
`-- package.json
Installing Dependencies
We’ll need the ‘express’ and ‘sitemap’ packages. Install them using npm:
npm install express sitemap
Creating a Basic Sitemap
Setting Up Express
Basic Express server setup with a route for the sitemap.
import express from 'express';
const app = express();
app.get('/sitemap.xml', function(req, res) {
// Sitemap generation logic will go here
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
Using ‘sitemap’ Package
Generate a sitemap using the ‘sitemap’ library.
import { SitemapStream, streamToPromise } from 'sitemap';
// ...previous code
app.get('/sitemap.xml', function(req, res) {
const sitemap = new SitemapStream({ hostname: 'https://example.com' });
sitemap.write({ url: '/', changefreq: 'daily', priority: 0.7 });
// Add more URLs to the sitemap as needed
sitemap.end();
streamToPromise(sitemap).then(sitemapOutput => {
res.header('Content-Type', 'application/xml');
res.send(sitemapOutput.toString());
});
});
Advanced Sitemap Features
Dynamic Sitemap Generation
Fetching URLs from a database or API and dynamically adding them to the sitemap.
// Assume we have an async function fetchUrlsFromDB() that returns a list of URLs
// ...previous code
app.get('/sitemap.xml', async function(req, res) {
const sitemap = new SitemapStream({ hostname: 'https://example.com' });
const urls = await fetchUrlsFromDB();
urls.forEach(url => {
sitemap.write({ url });
});
sitemap.end();
const sitemapOutput = await streamToPromise(sitemap);
res.header('Content-Type', 'application/xml');
res.send(sitemapOutput.toString());
});
Automated Sitemap Updates
Automating sitemap updates on a scheduled basis using cron jobs or similar schedulers.
// Install node-cron package
// ...previous code
// Set up a cron job
import cron from 'node-cron';
cron.schedule('0 0 * * *', function() {
// Fetch URLs and regenerate sitemap.
});
Conclusion
This tutorial outlined the process of creating an extensible XML sitemap generator with Node.js and Express. By using modern JavaScript features and the ‘sitemap’ library, we can boost a site’s SEO with a well-structured sitemap.