How to build a sitemap in Express.js?

Member

by mabelle , in category: SEO , a year ago

How to build a sitemap in Express.js?

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

1 answer

by jacey.lubowitz , a year ago

@mabelle 

Creating a sitemap in Express.js involves the following steps:


Step 1: Install the required packages


Install the following packages using npm:


npm install sitemap sitemap-stream


Step 2: Create a sitemap route


Create a new route in Express.js that generates the sitemap. To do this, add the following code to your Express.js app:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
const router = express.Router();
const { SitemapStream } = require('sitemap');
const { createGzip } = require('zlib');

router.get('/sitemap.xml', async (req, res, next) => {
    try {
        // Create a new sitemap object
        const sitemap = new SitemapStream({ hostname: 'https://example.com' });
        
        // Add URLs to the sitemap
        sitemap.write({ url: '/' });
        sitemap.write({ url: '/page1' });
        sitemap.write({ url: '/page2' });
        
        // End the sitemap stream
        sitemap.end();
        
        // Pipe the sitemap to the response
        res.header('Content-Type', 'application/xml');
        res.header('Content-Encoding', 'gzip');
        const pipeline = sitemap.pipe(createGzip());
        pipeline.pipe(res).on('error', (e) => { throw e; });
    } catch (err) {
        next(err);
    }
});


This route generates a sitemap that includes three URLs: the homepage (/), and two additional pages (/page1 and /page2).


Step 3: Register the sitemap route


Register the sitemap route in Express.js by adding the following code to your app:

1
app.use('/', router);


This tells Express.js to register the sitemap route under the root URL (/).


Step 4: Test your sitemap


To test your sitemap, start your Express.js app and navigate to /sitemap.xml in your web browser. You should see a sitemap that includes the URLs you added in step 2.


That's it! You now have a sitemap in Express.js that can improve the search engine visibility of your website.