<!--
  canonical-url: https://www.avonture.be/blog/docusaurus-easter-eggs
  published:     2026-07-13
  This is a static plain-Markdown mirror generated at build time.
  Visit the canonical URL above for the fully rendered page, with images and interactive components.
-->

# Meerkat Mischief: Sprinkling Easter Eggs Across my Blog

> A tour of eight small, discoverable easter eggs added to this Docusaurus blog — a hidden ASCII-art meerkat in the page source, a Konami-code sprite run, a console.log wink, a tab-away favicon swap, rotating 404 messages, a hidden sitemap comment and more — plus the real bugs (key-repeat, an AZERTY keyboard mismatch, a wrong emoji, a postBuild race condition, a blurry favicon) caught along the way.

---
![Meerkat Mischief: Sprinkling Easter Eggs Across my Blog](/img/v2/easter_eggs.webp)**TL;DR**Beyond the meerkat mascot already visible on this blog, this blog hides eight small, deliberately discoverable easter eggs: an ASCII-art meerkat sitting right in the page source, a `console.log` wink, rotating 404 messages, a Konami-code sprite run, a tab-away title/favicon swap, an `X-Powered-By` HTTP header, a print-stylesheet footer, and a hidden comment in `sitemap.xml`. This article walks through every one of them with the actual source code, and — more usefully — the real bugs we shipped and caught along the way: a key-repeat race in the Konami handler, an AZERTY keyboard mismatch a real user (not our tests) found, a wrong emoji codepoint, a Docusaurus `postBuild` concurrency gotcha, and a favicon that was unreadable until we redesigned the crop.You already know this site has a mascot: a meerkat that shows up on the 404 page, rides the "scroll to top" button, and hides in an [ASCII-art HTML comment](/blog/docusaurus-ascii-art) on every page. That last one got me thinking: if a comment in the page source is fun, what else could a curious visitor stumble upon?So, this week-end, I asked myself — and [Claude Code](/blog/claude-ia-spare-tokens) — a simple question: how far can we take this without it becoming annoying? The answer turned into eight small easter eggs — the ASCII-art comment revisited in detail, plus seven new additions — each following the same rule: **if you're not looking for it, you'll never see it.** No pop-ups, no confetti on page load, nothing that gets in a reader's way. Just quiet rewards for the curious.> **The one rule behind all of this:**
>
> Every easter egg on this list lives in the console, the source, the response headers, or a state the visitor has to trigger on purpose (leaving the tab, printing a page, typing a secret code). None of them ever appear in the normal reading flow.## 1. The one that started it all: an ASCII-art meerkat in the page sourceThis is the easter egg that inspired everything else on this list, so it earns the top spot. Press `CTRL`+`U` on any page of this blog — or right-click and choose "View Page Source" — and right after the opening `<!doctype html>` line, before a single visible pixel has been described, you'll find a meerkat drawn entirely in ASCII characters, sitting inside an HTML comment:> Screenshot — view-source:https\://www\.avonture.be/blog/ripgrep/
>
> ![CTRL-U - View source](/img/v2/suricate_ctrl_u.webp)It's invisible in the rendered page — an HTML comment never reaches the screen — and it doesn't cost a single byte of layout or a single line of visible markup. It's purely a reward for anyone curious enough to look at the raw response.Under the hood, a small `postBuild` plugin (`plugins/ascii-injector/index.mjs`) walks every generated HTML file after `yarn docusaurus build` finishes and inserts the contents of `src/data/banner.txt` as a comment right after the `<!doctype html>` tag. *The plugin itself is built step by step in [Inject ASCII Art in any HTML pages rendered by Docusaurus](/blog/docusaurus-ascii-art), and the banner comes from the same generator as the one in [Bash - ASCII art](/blog/bash-ascii-art):*```bash
$ yarn docusaurus build
$ grep -A2 doctype build/index.html
<!doctype html>
<!--
```> **Already covered in detail:**
>
> This one has its own dedicated article — [Inject ASCII Art in any HTML pages rendered by Docusaurus](/blog/docusaurus-ascii-art) — with the full plugin source, how to convert your own logo to ASCII art, and a `postBuild`-only caveat (it won't show up while running `yarn start` in dev mode, only on a real build). We won't repeat all of it here; this entry exists mainly so the egg gets its rightful place in this list.## 2. A console.log wink for DevTools visitorsThe easiest one. If you open your browser's DevTools console on this blog, you'll see this:**src/theme/Root.js (excerpt)**```javascript
// Excerpt from src/theme/Root.js

// Console easter egg: a little wink for visitors who open DevTools.
// Runs once per full page load, not on every client-side route change.
useEffect(() => {
  console.log(
    '%c \u{1F9AB} Curious, aren\'t you?',
    'font-size:18px;font-weight:bold;color:#e8871e;',
  );
  console.log(
    '%cThe meerkat sentry is watching this site too. If you enjoy digging around in the source, try the Konami code somewhere on this page...',
    'font-size:12px;color:#888;',
  );
}, []);
```Nothing fancy: a styled `console.log` call (the `%c` directive lets you apply CSS to console output) that fires once per full page load. It also doubles as a hint, pointing curious readers toward the Konami code below.![Console.log()](./images/console_log.webp)> **Why useEffect(..., \[]):**
>
> An empty dependency array means this effect runs once when the component mounts — not on every client-side route change. Since `Root` wraps the whole app and survives navigation between pages, this is the right place for a "once per visit" easter egg.## 3. A 404 page with a sense of humorThe 404 page already showed a meerkat illustration and a message. We turned the message into a small pool of five, picked at random on every load:**src/theme/NotFound/index.js**```javascript
import React, { useEffect, useState } from "react";
import Translate, { translate } from "@docusaurus/Translate";
import useBaseUrl from "@docusaurus/useBaseUrl";
import { PageMetadata } from "@docusaurus/theme-common";
import { useLocation } from "@docusaurus/router";
import Layout from "@theme/Layout";
import Link from "@docusaurus/Link";
import { openPalette } from "@site/src/components/CommandPalette/paletteBus";
import styles from "./styles.module.css";

/** Turns a failed URL's last segment into a plausible search query — "docker-cs-fixer" → "docker cs fixer". */
function guessQueryFromPath(pathname) {
  const segment = pathname.split("/").filter(Boolean).pop() ?? "";
  return segment.replace(/[-_]+/g, " ").trim();
}

/**
 * The five wordings, one picked at random per visit.
 *
 * Listed one `translate()` call at a time rather than mapped over an array of strings:
 * `yarn write-translations` reads the AST, so each `id`/`message` pair has to be a literal at
 * its own call site or the key is never extracted and the French page keeps the English text.
 */
function lostMessages() {
  return [
    translate({
      id: "theme.NotFound.lost.companions",
      message:
        "Don't worry, your meerkat companions are pointing the way back to the main burrow.",
    }),
    translate({
      id: "theme.NotFound.lost.sentries",
      message:
        "Our sentries scanned the horizon and found... nothing. This page doesn't exist.",
    }),
    translate({
      id: "theme.NotFound.lost.dug",
      message: "The meerkat colony dug everywhere and still couldn't find this page.",
    }),
    translate({
      id: "theme.NotFound.lost.tiptoes",
      message:
        "Even standing on their tiptoes, the meerkats can't spot this page anywhere.",
    }),
    translate({
      id: "theme.NotFound.lost.burrow",
      message: "This burrow is empty. The meerkats suggest heading back home.",
    }),
  ];
}

export default function NotFound() {
  const title = translate({
    id: "theme.NotFound.title",
    message: "Page Not Found",
  });
  const [message] = useState(() => {
    const messages = lostMessages();
    return messages[Math.floor(Math.random() * messages.length)];
  });
  // Front-matter-style static path: it carries no locale prefix of its own, so under `fr` a bare
  // "/img/404.webp" resolves to the SPA fallback and the illustration never paints.
  const imageUrl = useBaseUrl("/img/404.webp");
  const location = useLocation();
  const query = guessQueryFromPath(location.pathname);

  // The moment a visitor most needs the search tool is right here — open the command
  // palette pre-filled with the failed URL instead of waiting for them to find `Ctrl+K`.
  useEffect(() => {
    openPalette(query);
  }, [query]);

  return (
    <>
      <PageMetadata title={title} />
      <Layout>
        <main className="container margin-vert--xl">
          <div className="row">
            <div className="col col--6 col--offset-3 text--center">
              <img
                src={imageUrl}
                alt={translate({
                  id: "theme.NotFound.imageAlt",
                  message: "A group of meerkats looking confused.",
                })}
                className={styles.notFoundImg}
              />
              {/* Its own id: this used to reuse `theme.NotFound.title`, the <meta> title above.
                  English never showed it — a missing key falls back to each call's own
                  `message` — but as soon as French supplied one, both rendered "Page
                  introuvable" and the heading lost its wording. */}
              <h1 className="hero__title">
                {translate({
                  id: "theme.NotFound.heading",
                  message: "Oh no! It looks like you're lost.",
                })}
              </h1>
              <p>{message}</p>
              <Link to="/" className="button button--primary button--lg">
                {translate({
                  id: "theme.NotFound.backToHome",
                  message: "Take me back to the homepage",
                })}
              </Link>{" "}
              <button
                type="button"
                className="button button--secondary button--lg"
                onClick={() => openPalette(query)}
              >
                <Translate id="theme.NotFound.search">Search the site</Translate>
              </button>
            </div>
          </div>
        </main>
      </Layout>
    </>
  );
}
````useState(() => …)` with a function initializer ensures the random pick happens exactly once per mount, not on every re-render — important here since `NotFound` doesn't need to re-roll the message while the user reads it./* Deliberately a raw <a> and not a Markdown link: this URL has to stay dead for the
  demo to work, and Docusaurus's broken-link checker (`onBrokenLinks`) only collects
  \<Link> elements — which is what a Markdown link compiles to. Written as `[…](…)`
  it would fail every build. */Try it: Click on this link [inexisting\_page](/blog/inexisting_page) then press `F5` to get random message.## 4. The star of the show: a Konami code easter eggType `↑ ↑ ↓ ↓ ← → ← → B A` anywhere on this site (not in a text field) and a meerkat sprints across your screen. This is the one worth the most detail, because it's also the one that taught us the most.Here is our running merkat; try it out!![Running merkat](./images/konami.webp)More info about what's Konami code is?  Consult [this page](https://en.wikipedia.org/wiki/Konami_Code) on wikipedia.### The component**src/components/KonamiEasterEgg/index.tsx**```typescript
import { useEffect, useState, useRef, useCallback, type JSX } from "react";
import runningImg from "@site/static/img/meerkat/suricate_running.webp";
import styles from "./styles.module.css";
import { translate } from "@docusaurus/Translate";

const KONAMI_CODE = [
  "ArrowUp",
  "ArrowUp",
  "ArrowDown",
  "ArrowDown",
  "ArrowLeft",
  "ArrowRight",
  "ArrowLeft",
  "ArrowRight",
  "b",
  "a",
];

const ARROW_KEYS = new Set(["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight"]);

// Holding Shift to type "B"/"A" as capitals fires its own keydown for the
// modifier itself first (event.key === "Shift"). Left unguarded, that keydown
// doesn't match whatever arrow is next expected and resets progress to 0
// before the "B"/"A" keydown even arrives — so the last two letters could
// never be reached the moment someone shift-presses instead of typing plain
// lowercase b/a.
const MODIFIER_KEYS = new Set([
  "Alt",
  "AltGraph",
  "CapsLock",
  "Control",
  "Fn",
  "FnLock",
  "Meta",
  "NumLock",
  "ScrollLock",
  "Shift",
  "Symbol",
  "SymbolLock",
]);

// event.code reflects the physical key position on a QWERTY reference
// layout, so on an AZERTY keyboard the key printed "A" reports 'KeyQ'.
// event.key reflects the actual character produced, which matches what
// players see printed on their own keycaps regardless of layout.
const normalizeKey = (key: string) => (key.length === 1 ? key.toLowerCase() : key);

const RUN_DURATION_MS = 3000;

export default function KonamiEasterEgg(): JSX.Element | null {
  const [isRunning, setIsRunning] = useState(false);
  const progressRef = useRef(0);

  const triggerRun = useCallback(() => {
    setIsRunning(true);
    console.log(
      "%c\u{1F9AB} Konami code accepted! Run, meerkat, run!",
      "font-size:14px;font-weight:bold;color:#e8871e;",
    );
    window.setTimeout(() => setIsRunning(false), RUN_DURATION_MS);
  }, []);

  useEffect(() => {
    const handleKeyDown = (event: KeyboardEvent) => {
      // Ignore auto-repeated keydowns fired while a key is held down: a
      // slightly-too-long "ArrowUp" press would otherwise inject extra
      // events and break a sequence that has two of the same key in a row.
      if (event.repeat) return;
      // event.key can be undefined at runtime (IME composition, synthetic events,
      // older browser bugs) despite TypeScript's DOM types declaring it string.
      if (!event.key) return;
      if (MODIFIER_KEYS.has(event.key)) return;

      const key = normalizeKey(event.key);
      const expectedKey = KONAMI_CODE[progressRef.current];
      if (key === expectedKey) {
        if (ARROW_KEYS.has(key)) {
          // Stop the arrow keys from scrolling the page mid-sequence.
          event.preventDefault();
        }
        progressRef.current += 1;
        if (progressRef.current === KONAMI_CODE.length) {
          progressRef.current = 0;
          triggerRun();
        }
      } else {
        progressRef.current = key === KONAMI_CODE[0] ? 1 : 0;
      }
    };

    window.addEventListener("keydown", handleKeyDown);
    return () => window.removeEventListener("keydown", handleKeyDown);
  }, [triggerRun]);

  if (!isRunning) {
    return null;
  }

  return (
    <img
      src={runningImg}
      alt={translate({
        id: "konamiEasterEgg.alt",
        message: "A meerkat sprinting across the screen",
      })}
      className={styles.runner}
    />
  );
}
```The logic keeps a `useRef` cursor into a `KONAMI_CODE` array of [`KeyboardEvent.code`](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/code) values (not `.key` — `.code` reflects the physical key position, so the sequence works the same on an AZERTY keyboard as on a QWERTY one). Each keydown either advances the cursor, resets it, or — on a full match — mounts a runner `<img>` for 3 seconds:**src/components/KonamiEasterEgg/styles.module.css**```css
.runner {
  position: fixed;
  bottom: 24px;
  left: -160px;
  width: 140px;
  height: auto;
  z-index: 9999;
  pointer-events: none;
  animation: run-across 3s linear forwards;
}

@keyframes run-across {
  from {
    left: -160px;
  }
  to {
    left: 100vw;
  }
}

@media (prefers-reduced-motion: reduce) {
  .runner {
    animation: none;
    left: 50vw;
  }
}
```It's mounted once, globally, from `src/theme/Root.js`:```jsx title="src/theme/Root.js (excerpt)"
import KonamiEasterEgg from '@site/src/components/KonamiEasterEgg';

// ...

return (
  <>
    {children}
    <KonamiEasterEgg />
  </>
);
```> **Try it right now:**
>
> Seriously — click anywhere on this page to make sure it has focus, then type `↑ ↑ ↓ ↓ ← → ← → B A`. This exact component is running on the page you're reading.### The bug that nearly killed the funAfter shipping this, real-world testing turned up a genuine bug: typed slowly and deliberately, the sequence sometimes just... didn't trigger. The cause was auto-repeat. Hold `ArrowUp` even a fraction of a second too long — which is very natural when you're carefully recalling a sequence — and the browser fires several `keydown` events with `repeat: true` before you release the key. Since the sequence needs `ArrowUp` **twice in a row**, one held press can inject an extra `ArrowUp` event right when the handler expects `ArrowDown`, silently resetting the whole thing.The fix is one guard clause:```jsx title="src/components/KonamiEasterEgg/index.tsx (excerpt)"
const handleKeyDown = (event) => {
  // Ignore auto-repeated keydowns fired while a key is held down: a
  // slightly-too-long "ArrowUp" press would otherwise inject extra
  // events and break a sequence that has two of the same key in a row.
  if (event.repeat) return;

  // ...
};
```We verified the fix with [Playwright](https://playwright.dev/) rather than just eyeballing it — dispatching a synthetic `keydown` with `repeat: true` confirmed the handler now ignores it, and a full quick-tap run of the sequence still triggers the animation. If your easter egg (or any keyboard shortcut, really) involves two identical keys back-to-back, don't skip this check.### The bug a real user found that automated testing missedThe key-repeat fix shipped, tests were green — and the feature still didn't work for a real visitor. The report: "I try the combination but nothing happens." The cause turned out to be the keyboard, not the code: on a Belgian AZERTY keyboard, the physical key printed **A** sits exactly where a QWERTY keyboard has **Q** (and vice-versa). The original implementation matched on [`event.code`](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/code), which reports the *physical position* of the key on a QWERTY reference layout — so pressing the keycap labeled "A" on an AZERTY keyboard produced `code: 'KeyQ'`, not `'KeyA'`. The user's own diagnosis nailed it: typing what looked like "B, Q" on their keyboard worked, because that physical position maps to `KeyA`.The fix is to match on [`event.key`](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key) instead — the actual character produced, which respects whatever layout the visitor has configured:```jsx title="src/components/KonamiEasterEgg/index.tsx (excerpt)"
// event.code reflects the physical key position on a QWERTY reference
// layout, so on an AZERTY keyboard the key printed "A" reports 'KeyQ'.
// event.key reflects the actual character produced, which matches what
// players see printed on their own keycaps regardless of layout.
const normalizeKey = (key) => (key.length === 1 ? key.toLowerCase() : key);

// ...

const key = normalizeKey(event.key);
if (key === expectedKey) { /* ... */ }
```Arrow keys were never affected — `ArrowUp`, `ArrowDown`, `ArrowLeft`, `ArrowRight` are identical strings for both `.code` and `.key` on every layout. The bug only bit the two letter keys at the end of the sequence, and only for the roughly [15–20% of keyboards worldwide](https://en.wikipedia.org/wiki/Keyboard_layout) that aren't QWERTY.> **Lesson:**
>
> Our Playwright test caught the key-repeat regression because it dispatched real, sequential events — but it never caught the layout bug, because Playwright's virtual keyboard defaults to QWERTY. Automated tests validate the logic you thought to test; they don't replace a human with different hardware. If a feature involves typed input, `.key` is almost always the right choice over `.code` — reserve `.code` for cases where you deliberately want physical key position (game movement controls, for instance, where WASD should stay in the same physical spot regardless of layout).## 5. Tab-away easter egg: title and favicon swapLeave this tab and come back — the title changes to "Come back, the meerkat is on watch! 👀" and the favicon swaps to a dozing meerkat. Both revert the instant the tab regains focus:![Inactive tab](./images/inactive_tab.webp)**src/theme/Root.js (excerpt)**```javascript
// Excerpt from src/theme/Root.js

const sleepingFaviconUrl = useBaseUrl('/img/favicon-sleeping.png');

// Title bar easter egg: greet visitors who leave the tab and come back,
// swapping the favicon for a dozing meerkat while they're away.
useEffect(() => {
  const originalTitle = document.title;
  const faviconLink = document.querySelector('link[rel="icon"]');
  const originalFavicon = faviconLink?.href;

  const handleVisibilityChange = () => {
    if (document.hidden) {
      document.title = 'Come back, the meerkat is on watch! \u{1F440}';
      if (faviconLink) faviconLink.href = sleepingFaviconUrl;
    } else {
      document.title = originalTitle;
      if (faviconLink && originalFavicon) faviconLink.href = originalFavicon;
    }
  };

  document.addEventListener('visibilitychange', handleVisibilityChange);
  return () =>
    document.removeEventListener('visibilitychange', handleVisibilityChange);
}, [location, sleepingFaviconUrl]);
```The `visibilitychange` event and `document.hidden` are the standard way to detect this — no polling needed. `useBaseUrl` (a Docusaurus hook) resolves the favicon path correctly regardless of the site's configured base URL, the same helper used elsewhere on this site for image sources.## 6. A wink in the HTTP headersThis one is invisible unless you check the Network tab or run `curl -I`. It lives in `nginx.conf`, right in the HTTPS server block:**nginx.conf**```conf
# nginx.conf

# 1. HTTP to HTTPS Redirection (Optional but recommended)
server {
    listen 80;
    server_name localhost;
    # Redirect all HTTP traffic to HTTPS, preserving the path and query string
    return 301 https://$host$request_uri;
}

# 2. HTTPS Server Block (The main site configuration)
server {
    listen 443 ssl http2;

    # Root directory where Docusaurus files are located
    root /usr/share/nginx/html;

    # Index file
    index index.html index.htm;

    server_name localhost;

    # SSL Configuration — mount real certs at runtime:
    # docker run -v /path/to/certs:/etc/nginx/certs:ro blog-docusaurus:production
    ssl_certificate /etc/nginx/certs/fullchain.pem;
    ssl_certificate_key /etc/nginx/certs/privkey.pem;

    # Basic SSL settings (Recommended)
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_prefer_server_ciphers on;
    ssl_ciphers HIGH:!aNULL:!MD5;

    # Easter egg: a little wink for anyone inspecting the response headers.
    add_header X-Powered-By "Meerkat-Sentry/1.0" always;

    # --- Docusaurus Home Page Redirection ---
    # When a user hits the root (https://localhost/), redirect them to /blog
    location = / {
        return 301 /blog;
    }

    # Mirrors static/.htaccess, which is what actually serves the site today.
    #
    # The classic "rewrite everything to index.html" SPA fallback is deliberately
    # NOT used: Docusaurus pre-renders its routes to files, so that fallback
    # catches almost nothing real and just makes the server answer 200 to every
    # URL on earth. That is a soft 404 — Google treats it as a quality signal, no
    # dead-link checker can work against a server that never says no, and a feed
    # reader polling a removed /blog/tags/<slug>/rss.xml would get HTML with a
    # 200 instead of a clean 404.
    #
    # What survives of it is this narrow safety net for the two route families
    # that are generated rather than authored — the tag and series pages
    # registered by plugins/docusaurus-plugin-tag-route and
    # docusaurus-plugin-series-route. When a per-slug file exists in the build,
    # try_files serves it and the fallback never fires; it only takes over when
    # the file is missing, which is exactly when the React router still knows how
    # to render the page and a 404 would be wrong.
    #
    # One path segment only, on purpose: /blog/tags/tags/<slug> is the blog
    # plugin's own listing and a real directory, /blog/tags/a/b is not a route at
    # all, and /blog/tags/<slug>/rss.xml is a file — all three must fall through
    # to the 404 below rather than be answered with index.html.
    location ~ ^/(series|blog/tags)/[^/]+/?$ {
        try_files $uri $uri/ /index.html;
    }

    # Anything else: a file on disk, or a real 404. Docusaurus already builds
    # 404.html from the theme, so the reader gets the site's own styled error
    # page rather than nginx's grey default.
    location / {
        try_files $uri $uri/ =404;
    }

    error_page 404 /404.html;

    location = /404.html {
        internal;
    }

    # Cache control for static assets (optional, but good practice)
    location ~* \.(?:css|js|jpe?g|gif|png|ico|woff2?|ttf|eot|svg)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
        try_files $uri =404;
    }
}
````add_header X-Powered-By "Meerkat-Sentry/1.0" always;` — a small, harmless header for anyone who inspects response headers out of habit.## 7. Print stylesheet easter eggPrint an article (`Ctrl+P`) and a small footer note appears on the printed page:**src/css/custom.css (excerpt)**```css
/* Excerpt from src/css/custom.css */

/* --- PRINT EASTER EGG --- */
/* A small nod to the meerkat mascot for anyone who prints an article. */

@media print {
  body::after {
    content: "\1F9AB Printed from avonture.be \2014 mascot-approved reading material.";
    position: fixed;
    bottom: 10px;
    left: 0;
    right: 0;
    text-align: center;
    font-size: 9px;
    color: #999;
  }
}
````@media print` only applies its rules when the browser is generating a print preview or an actual printout — it's invisible in the normal browsing experience, which is exactly the point.## 8. Sitemap.xml gets a comment tooThe least likely to ever be found, and the one that produced the most interesting bug. The idea: slip a small XML comment as the first child of `<urlset>` in the generated `sitemap.xml`. A comment there is valid XML and ignored by every sitemap parser and crawler, so it can't break indexing.**plugins/sitemap-easter-egg/index.mjs**```mjs
/**
 * Docusaurus Plugin: sitemap-easter-egg
 *
 * Purpose:
 * Slips a small, valid XML comment right after the <urlset> opening tag of the
 * generated sitemap.xml, for the rare visitor who reads sitemaps for fun.
 *
 * A comment placed as the first child of <urlset> is valid XML and is ignored
 * by every sitemap parser/crawler, so it can't break indexing.
 *
 * Usage:
 * - Save this plugin as `plugins/sitemap-easter-egg/index.mjs`
 * - Add it to `docusaurus.config.js` plugins array.
 *
 * Note: Docusaurus runs every plugin's postBuild hook concurrently, so the
 * official sitemap plugin may not have written sitemap.xml yet when this
 * hook starts. We poll briefly for the file before giving up.
 */

import { promises as fs } from "node:fs";
import path from "node:path";

const POLL_ATTEMPTS = 15;
const POLL_INTERVAL_MS = 300;

async function readWhenReady(filePath) {
  for (let attempt = 0; attempt < POLL_ATTEMPTS; attempt += 1) {
    try {
      return await fs.readFile(filePath, "utf8");
    } catch (err) {
      if (err.code !== "ENOENT" || attempt === POLL_ATTEMPTS - 1) {
        throw err;
      }
      await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));
    }
  }
  return undefined;
}

export default function sitemapEasterEggPlugin() {
  return {
    name: "sitemap-easter-egg-plugin",

    async postBuild({ outDir, siteConfig }) {
      const sitemapPath = path.resolve(
        outDir,
        siteConfig?.presets?.[0]?.[1]?.sitemap?.filename || "sitemap.xml",
      );

      let xml;
      try {
        xml = await readWhenReady(sitemapPath);
      } catch (err) {
        console.warn(
          `[sitemap-easter-egg] sitemap.xml not found, skipping: ${err.message}`,
        );
        return;
      }

      const comment =
        "<!-- Hi there! A meerkat sentry reviewed every URL in this sitemap. -->";

      if (xml.includes(comment)) {
        return;
      }

      const urlsetTag = /<urlset[^>]*>/i;
      if (!urlsetTag.test(xml)) {
        console.warn("[sitemap-easter-egg] <urlset> tag not found, skipping.");
        return;
      }

      const updated = xml.replace(urlsetTag, (m) => `${m}${comment}`);
      await fs.writeFile(sitemapPath, updated, "utf8");
      console.log("[sitemap-easter-egg] Comment injected into sitemap.xml");
    },
  };
}
```Registered the same way as the [ASCII-art injector](/blog/docusaurus-ascii-art):**docusaurus.config.js (excerpt)**```javascript
// [...]
plugins: [
    // [...]
    [
        "./plugins/ascii-injector/index.mjs",
        { bannerPath: "src/data/banner.txt" },
    ],
    "./plugins/sitemap-easter-egg/index.mjs",
],
```## What we ended up with**The eight easter eggs**- **ASCII-art meerkat** — hidden in the page source, right after `<!doctype html>`

- **Console.log wink** — a styled message for anyone with DevTools open

- **Rotating 404 messages** — five random, mascot-flavored variants

- **Konami code** — `↑ ↑ ↓ ↓ ← → ← → B A` sends a meerkat running across the screen

- **Tab-away swap** — title and favicon change while the tab is hidden, and revert on return

- **X-Powered-By header** — a wink in the HTTP response headers

- **Print stylesheet** — a small footer note on printed pages

- **Sitemap.xml comment** — a hidden, XML-valid comment as the first child of `<urlset>`None of these change how a single reader reads a single article. That was the whole point — a blog's job is still to be read, not to perform tricks at the reader. But for the developers, the crawlers, the DevTools-curious, and the people who actually print articles or inspect response headers, there's now a little more personality hiding just under the surface. So cool no?That list has since grown by one: every egg above assumes a keyboard or an open DevTools panel, which is no use to anyone reading on a phone — so [shaking the phone](/blog/docusaurus-shake-easter-egg) now startles the mascot full-screen for a couple of seconds, no keyboard involved.If you're running your own Docusaurus blog and have a mascot, a logo, or even just a favorite color: pick one or two of these — they're all small, self-contained, and none of them require touching your actual content. Start with the one that matches where your readers already are (DevTools console if your audience is developers, HTTP headers if it's other bloggers who poke at things, print CSS if people print your recipes or tutorials) and grow from there.
