Eleventy Recipes: Git Hash, Last Modified, Feeds, Offline, WebSub

Seven recipes from brennan.day's Eleventy build: a git commit hash in the footer, automatic last-modified dates, an RSS feed, build-time status.lol data, markdown-it plugins, a service worker for offline reading, and a WebSub ping after deploy.

By
Brennan Kenneth Brown
Published
Reading time
2 minutes
Level
Intermediate
You need
  • An Eleventy project
  • Basic JavaScript and Nunjucks
Open book with pages of patterned color swatches

These seven Eleventy recipes come from the build behind brennan.day: a git commit hash in the footer, automatic last-modified dates, an RSS feed, build-time data from status.lol, markdown-it plugins, a service worker for offline reading, and a WebSub ping after each deploy. Each section is independent, so you can use any of them on its own. The snippets go in your Eleventy config file (.eleventy.js here) unless noted.

The site footer displays the current git commit hash and build date, linking to the commit on GitLab. This shows when the site was last built and helps with debugging. The snippet needs execSync imported from child_process.

eleventyConfig.addGlobalData("gitCommit", () => {
  try {
    return execSync('git rev-parse --short HEAD').toString().trim();
  } catch(e) {
    return 'unknown';
  }
});

How do I add automatic last-modified dates?

I used to add "Last Updated" to pages by hand. Now all posts and pages show a "last modified" date based on the file's timestamp. For posts, it only shows if the modification date differs from the publish date:

<!-- In post.njk -->
{% set lastMod = page.inputPath | lastModified %}
{% set publishDate = page.date | readableDate %}
{% if lastMod and lastMod != publishDate %}
<div class="post-meta-item">
  <i class="fas fa-pencil-alt" aria-hidden="true"></i>
  <span>Last modified: {{ lastMod }}</span>
</div>
{% endif %}

<!-- In page.njk -->
{% set lastMod = page.inputPath | lastModified %}
{% if lastMod %}
<footer class="page-footer">
  <p class="page-meta">
    <i class="fas fa-pencil-alt" aria-hidden="true"></i>
    <span>Last modified: {{ lastMod }}</span>
  </p>
</footer>
{% endif %}

This uses a custom lastModified filter in .eleventy.js that reads the file's timestamp and formats it. The conditional in the post template hides "Last modified" when it matches the publish date. On Netlify, a git-based version of this filter can hit cloning limits; see reducing Netlify build minutes for the details I ran into.

How do I build a valid RSS feed in Eleventy?

I wrote scripts to validate both the RSS and JSON feeds against their specs. The feeds include:

  • Author cards with h-card microformats
  • HTML cleanup filters to remove navigation from excerpts
  • Timezone-aware date handling
  • Proper content vs. summary distinction
// RSS feed validation and improvements
const { Feed } = require('feed');
const { DateTime } = require('luxon');

const feed = new Feed({
  title: "brennan.day",
  description: "Personal site and blog",
  id: "https://brennan.day/",
  link: "https://brennan.day/",
  language: "en",
  image: "https://brennan.day/assets/images/brennan.jpg",
  favicon: "https://brennan.day/favicon.ico",
  copyright: "CC BY-SA 4.0",
  feedLinks: {
    rss: "https://brennan.day/feed.xml",
    json: "https://brennan.day/feed.json"
  },
  hub: "https://pubsubhubbub.superfeedr.com/" // WebSub hub
});

// Add posts with proper timezone handling
collection.posts.forEach(post => {
  const date = DateTime.fromJSDate(post.date, { 
    zone: "America/Edmonton" 
  });
  
  feed.addItem({
    title: post.data.title,
    id: `https://brennan.day${post.url}`,
    link: `https://brennan.day${post.url}`,
    description: post.data.summary,
    content: post.content, // Full content
    date: date.toJSDate(),
    published: date.toJSDate()
  });
});

How do I fetch status.lol data at build time?

The sidebar displays my latest status update from status.lol, fetched via the omg.lol API during the build with @11ty/eleventy-fetch. The same data also feeds the twtxt feed.

Note: The Mastodon URL renders incorrectly in the status data, so I wrote a custom script to fix it.

// Fetch status.lol updates at build time
const EleventyFetch = require("@11ty/eleventy-fetch");

eleventyConfig.addGlobalData("statuslog", async () => {
  try {
    let json = await EleventyFetch(
      "https://api.omg.lol/address/brennan/statuses/",
      {
        duration: "1h", // Cache for 1 hour
        type: "json"
      }
    );
    
    // Transform statuses for display
    return json.response.statuses.map(status => ({
      emoji: status.emoji || '',
      content: status.content,
      created: new Date(parseInt(status.created) * 1000),
      relativeTime: status.relative_time
    }));
  } catch (error) {
    console.error('Failed to fetch status.lol:', error);
    return [];
  }
});

Which markdown-it plugins are useful for a blog?

I added these markdown-it plugins:

  • Footnotes for academic-style citations
  • Definition lists for glossaries
  • Abbreviations with automatic <abbr> tags
  • Insert/mark for highlighting changes

They add writing options without requiring raw HTML.

// Markdown-it extensions configuration
const markdownIt = require("markdown-it");
const markdownItFootnote = require("markdown-it-footnote");
const markdownItDeflist = require("markdown-it-deflist");
const markdownItAbbr = require("markdown-it-abbr");
const markdownItIns = require("markdown-it-ins");
const markdownItMark = require("markdown-it-mark");

let mdOptions = {
  html: true,
  breaks: false,
  linkify: true
};

let md = markdownIt(mdOptions)
  .use(markdownItFootnote)    // [^1] footnote syntax
  .use(markdownItDeflist)     // term : definition lists
  .use(markdownItAbbr)        // *[HTML]: HyperText Markup Language
  .use(markdownItIns)         // ++inserted text++
  .use(markdownItMark);       // ==marked text==

eleventyConfig.setLibrary("md", md);

How do I make an Eleventy site work offline with a service worker?

I added a service worker that caches the site for offline browsing. Once a page has been visited, it can be read without an internet connection. The simplified version below pre-caches a few static assets, caches other responses as they are fetched, and serves an /offline/ page when a navigation fails. You also need to register the worker from your site JavaScript.

// Service worker for offline support
const CACHE_NAME = 'brennan-day-v1';
const STATIC_ASSETS = [
  '/',
  '/assets/css/stylesheet.css',
  '/assets/js/main.js',
  '/offline/'
];

// Install event: cache static assets
self.addEventListener('install', (event) => {
  event.waitUntil(
    caches.open(CACHE_NAME)
      .then(cache => cache.addAll(STATIC_ASSETS))
  );
});

// Fetch event: serve from cache, fallback to network
self.addEventListener('fetch', (event) => {
  event.respondWith(
    caches.match(event.request)
      .then(response => {
        // Return cached version or fetch from network
        return response || fetch(event.request)
          .then(fetchResponse => {
            // Cache successful responses
            return caches.open(CACHE_NAME)
              .then(cache => {
                cache.put(event.request, fetchResponse.clone());
                return fetchResponse;
              });
          });
      })
      .catch(() => {
        // Return offline page for navigation requests
        if (event.request.mode === 'navigate') {
          return caches.match('/offline/');
        }
      })
  );
});

How do I add WebSub to an Eleventy site?

WebSub (formerly PubSubHubbub) lets feed subscribers receive new posts immediately instead of polling. I added it after Scan.FYI, a tool by Ritual that checks which IndieWeb protocols a site supports, showed 8 of 9. The RSS feed includes the hub link, and a script pings the hub after each deploy.

// WebSub ping after site deploy
const fetch = require('node-fetch');

async function pingWebSubHub() {
  const hubUrl = 'https://pubsubhubbub.superfeedr.com/';
  const topicUrl = 'https://brennan.day/feed.xml';
  
  const params = new URLSearchParams({
    'hub.mode': 'publish',
    'hub.url': topicUrl
  });
  
  try {
    const response = await fetch(hubUrl, {
      method: 'POST',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      body: params
    });
    
    console.log('WebSub ping:', response.status);
  } catch (error) {
    console.error('WebSub ping failed:', error);
  }
}

// Call after a successful deploy
pingWebSubHub();