Easily Generate a Sitemap for Your Website with Node.js

aman pareek author
Aman Pareek

Published 11/11/2024

Updated 11/11/2024

Hey everyone! While working on my website, I needed to generate a sitemap. I ended up creating a simple and easy-to-use solution in the form of an npm package—and I thought, why not share it with you all? This package makes it super easy to generate sitemaps for your website in Node.js. Whether you're building a small site or a large-scale application, this tool can help you get your sitemap up and running in no time.

In this post, I'll show you how to use the package and get started with generating sitemaps effortlessly. Let’s dive in!

Step 1: Install the Package

To get started, you’ll first need to install the package using npm. Run the following command:

Shell

            npm i ap-sitemap
        

Step 2: Create a Sitemap Instance

Once the package is installed, you can create a sitemap instance. Simply require the package and configure it with your site’s details. Here's an example of how you can set it up:

JavaScript

            const SiteMapGenerator = require('ap-sitemap');

const sitemap = new SiteMapGenerator({
  baseUrl: 'https://yourwebsite.com',  // Replace with your website's URL
  outDir: 'dist', // Output directory for the sitemap (default is 'build')
  limit: 50000, // Maximum number of URLs in the sitemap (default is 50,000)
  removeIndexExtension: true, // Removes '/index.html' or other extensions from URLs
});
        

Step 3: Add Pages to Your Sitemap

Next, you'll want to add pages to your sitemap. You can specify the URL, last update time, change frequency, and priority for each page. Here's an example of how you can add multiple pages:

JavaScript

            sitemap.addPages([
  {
    url: 'https://example.com/page1',
    updatedAt: '2024-11-04T10:00:00Z',
    changefreq: 'daily',
    priority: 1.0,
  },
  {
    url: 'https://example.com/page2',
    updatedAt: '2024-11-03T10:00:00Z',
    changefreq: 'weekly',
    priority: 0.8,
  },
]);
        

Step 4: Generate the Sitemap

Finally, you can generate your sitemap with a simple function call. This will create a sitemap.xml file in the output directory you specified (e.g., dist/).

JavaScript

            const sitemapUrl = generator.generate(); // https://yourwebsite.com/sitemap.xml