Last Updated: December 19, 2019
·
12.43K
· 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.

sitemap.xml

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 = 'http://www.example.com'
  now = moment(new Date).format 'YYYY-MM-DD'

  errors = {}
  await
    Category.find()
      .select('key')
      .where('activeOffersCount').gt(0)
      .lean().exec defer errors.categories, categories
    ...
    Product.find()
      .select('uid date')
      .sort('-createdAt')
      .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
urlset(xmlns="http://www.sitemaps.org/schemas/sitemap/0.9")

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

  ...

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

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

And you're done.

Have a fresh tip? Share with Coderwall community!

Post
Post a tip