Last Updated: December 19, 2019
· Ionut-Cristian Florescu

Straightforward sitemap.xml generation in Node.js applications

It is my opinion that, provided one has enough real-life coding experience and knows his way around the ecosystem, Node.js is perfectly suitable not only for small API projects, but for building generic web projects as well.

One of the SEO-related tasks you have to deal with when building a generic web project is generating a sitemap.xml file.


While there are certainly a number of modules out there that might help you with this task, there's an easy, straightforward and dependency-free way to do it.

Setup a route (or controller method) to respond to get /sitemap.xml with the relevant information - in this case I'm using IcedCoffeeScript for elegant asynchronous control flow - and make sure to set the response content-type to application/xml:

callback: (req, res, next) ->
  appUrl = ''
  now = moment(new Date).format 'YYYY-MM-DD'

  errors = {}
      .lean().exec defer errors.categories, categories
      .select('uid date')
      .lean().exec defer errors.products, products

    for own operation, err of errors
      return next err if err

    res.header 'Content-Type', 'application/xml'
    res.render 'public/sitemap', { appUrl, now, categories, products }

Then, in your view - I'm using Jade, so in this case it's sitemap.jade - you can have something like this:

!!! xml

  //- Home page
    loc= appUrl
    lastmod= now
    changefreq daily
    priority= 0.8


  //- Categories
  each category in categories
      loc #{appUrl}/offers/#{category.key}
      lastmod= now
      changefreq daily
      priority= 0.7

  //- Products
  each product in products
      loc #{appUrl}/#{product.uid}.html
      changefreq weekly
      priority= 0.5

And you're done.

Have a fresh tip? Share with Coderwall community!

Post a tip