Adding sitemap.xml to an 11ty v3.0 site

Adding sitemap.xml to an 11ty v3.0 site

7 min read
11ty websites

Sitemaps are fundamental in helping search engines discover and index your website's content efficiently. I recently rebuilt this site on 11ty, a static site generate based on Node. I was surprised to see that there wasn't an official plugin for sitemap.xml support (presumably because of the flexibility of the tool...), so I dug in myself. I came across another article on this topic, so much of this is a rehash for my own understanding.

As with many things in Eleventy, there's no one way to so things. I played with two implementation approaches, both of which I'll outline.

Before you get started, make sure that site.url has been set up in your project.

Configure the template

Add a sitemap.njk to the root of your project and include the following.

---
# sitemap.njk
layout: null
permalink: sitemap.xml
eleventyExcludeFromCollections: true
--- 
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  {% for item in collections.all %}
    {% if item.data.excludeFromSitemap != true %}
      <url>
        <loc>{{ site.url }}{{ item.url }}</loc>
      </url>
    {% endif %}
  {% endfor %}
</urlset>

How It Works

The sitemap generator works through several key components:

  1. Front Matter Configuration:

    • layout: null ensures no template wrapping
    • permalink: sitemap.xml sets the output file name
    • eleventyExcludeFromCollections: true prevents the sitemap itself from being included in collections
  2. Dynamic URL Generation:

    • Iterates through all site content using collections.all
    • Allows exclusion of specific pages using excludeFromSitemap flag
    • Combines base URL with page paths to create absolute URLs

Key Features

1. Automatic URL Collection

The generator collects all pages in your site through 11ty's collections system, so new entries will automatically be added to your sitemap.

2. Selective Exclusion

By adding excludeFromSitemap: true to any page's front matter, you can easily exclude specific pages from the sitemap. Adding

---
excludeFromSitemap: true
---

to any page's front matter will exclude it from the sitemap without excluding it from all collections like you would with eleventyExcludeFromCollections.

Further Enhancement

If your posts have a date property, you can add this to your sitemap as well.

<url>
  <loc>{{ site.url }}{{ item.url }}</loc>
  <!-- If the post has a date, use it as the last modified -->
  {% if item.data.date %}
  <lastmod>{{ item.data.date | dateISO }}</lastmod>
  <changefreq>monthly</changefreq>
  {% endif %}
</url>

You may need the dateISO filter I'm using in my example as well...

// in your eleventy.config.mjs or equivalent.
eleventyConfig.addFilter('dateISO', function (date) {
    return new Date(date).toISOString();
});