<!--
  canonical-url: https://www.avonture.be/blog/docusaurus-reactions
  published:     2026-07-27
  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.
-->

# Adding Reader Reactions to Your Docusaurus Blog

> Build a fully working "Was this article helpful?" widget for your Docusaurus blog. Step-by-step guide covering the PHP backend, React component, CSS module, Docusaurus swizzle, and an admin dashboard — everything you need to reproduce it from scratch.

---
![Adding Reader Reactions to Your Docusaurus Blog](/img/v2/docusaurus_like_button.webp)

**TL;DR**

This guide walks through building a "Was this article helpful?" widget for a Docusaurus blog — from scratch, end to end. You will create a lightweight PHP script that stores votes in a JSON file and sends throttled email notifications, a React component that reads and writes those votes, a CSS module that blends seamlessly with any Docusaurus theme, and a swizzle of `BlogPostItem` to inject the widget **at the bottom** of every post. A bonus admin dashboard page lets you monitor approval rates across all articles at a glance.

Reader feedback is one of those things that looks simple from the outside but hides a surprising amount of moving parts once you start building it. I wanted something unobtrusive — no third-party services, no cookies, no sign-up required. Just a small "Was this article helpful?" widget at the bottom of every post, a JSON file on the server, and an email in my inbox when a reader votes.

What followed was a self-contained system: a 160-line PHP backend, a React component, a CSS module, and a single swizzle. Everything lives in your own repository and under your own hosting. No external dependencies, no privacy implications, no recurring costs.

In this article I'll walk you through every file, every decision, and every line that matters — so you can reproduce it on your own Docusaurus blog and adapt it to your needs.

**Quick Jump:** [The Big Picture](#the-big-picture) | [All Files at a Glance](#all-files-at-a-glance)

> Screenshot — https\://www\.avonture.be/blog/docusaurus-easter-eggs
>
> ![Reactions](./images/reactions.webp)

## The Big Picture

Before diving in, here is what we are going to build and how the pieces fit together:

```plaintext
Browser                          Your Server
  │                                   │
  ├─ GET /api/reactions.php?slug=...  ─▶  reactions-data.json (read)
  │◀─ { helpful: 12, not_helpful: 3 } ─┤
  │                                   │
  ├─ POST /api/reactions.php          ─▶  reactions-data.json (write)
  │  { slug, vote }                   │   + email notification
  │◀─ { helpful: 13, not_helpful: 3 } ─┤
  │                                   │
  └─ GET /api/reactions.php?admin=... ─▶  reactions-data.json (full dump)
```

**Five files are involved:**

| File                                        | Role                                                  |
| ------------------------------------------- | ----------------------------------------------------- |
| `api/reactions.php`                         | PHP backend: stores votes, sends emails               |
| `src/components/Reaction/index.tsx`         | React component rendered at the bottom of every post  |
| `src/components/Reaction/styles.module.css` | CSS module for the widget                             |
| `src/theme/BlogPostItem/index.js`           | Swizzled Docusaurus component that injects the widget |
| `src/pages/reactions-dashboard.js`          | Admin page to visualize all votes                     |

Two JSON files are created at runtime by the backend:

* `api/reactions-data.json` — the vote store, one entry per article slug
* `api/notifications.json` — throttle timestamps, one entry per article slug

Let's build them one by one.

***

## Step 1 — The PHP backend

Create the file `api/reactions.php` at the root of your web server (next to, or inside, your Docusaurus output folder). The PHP script does not need to be inside the Docusaurus source tree at all; it just needs to be reachable by the browser.

### 1.1 — Configuration

**api/reactions.php**

```php
<?php
declare(strict_types=1);

// ── Configuration ─────────────────────────────────────────────────────────────
// Copy api/.env.example to api/.env and set your values before deploying.
$_envVars = file_exists(__DIR__ . '/.env')
    ? (parse_ini_file(__DIR__ . '/.env') ?: [])
    : [];

define('ADMIN_EMAIL',            $_envVars['ADMIN_EMAIL'] ?? '');
define('ADMIN_TOKEN',            $_envVars['ADMIN_TOKEN'] ?? '');
define('NO_REPLY',               $_envVars['NO_REPLY'] ?? '');
define('NOTIFY_COOLDOWN_SECONDS', 3600);   // minimum gap between emails per article
define('SITE_URL',               'https://www.avonture.be');

// ── CORS ──────────────────────────────────────────────────────────────────────
$allowedOrigins = [
    SITE_URL,
    'https://localhost:3000',
];

// Same-origin requests carry no Origin header — allow them unconditionally.
// Only cross-origin requests need to be validated.
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';
if ($origin !== '' && !in_array($origin, $allowedOrigins, true)) {
    http_response_code(403);
    exit;
}

header('Content-Type: application/json; charset=utf-8');
if ($origin !== '') {
    header("Access-Control-Allow-Origin: $origin");
    header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
    header('Access-Control-Allow-Headers: Content-Type');
    header('Vary: Origin');
}

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(204);
    exit;
}

// ── Helpers ───────────────────────────────────────────────────────────────────

function loadData(string $file): array
{
    if (!file_exists($file)) {
        return [];
    }
    return json_decode(file_get_contents($file), true) ?: [];
}

function saveData(string $file, array $data): void
{
    $fp = fopen($file, 'c+');
    if (!$fp) {
        return;
    }
    if (flock($fp, LOCK_EX)) {
        ftruncate($fp, 0);
        rewind($fp);
        fwrite($fp, json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
        flock($fp, LOCK_UN);
    }
    fclose($fp);
}

function sanitizeSlug(string $raw): string
{
    $slug = preg_replace('/[^a-z0-9\-\/]/', '', strtolower(trim($raw)));
    return substr($slug, 0, 200);
}

function jsonError(int $code, string $message): never
{
    http_response_code($code);
    echo json_encode(['error' => $message]);
    exit;
}

// Sends an email notification for a new vote, with a per-article cooldown.
function maybeNotify(string $slug, string $vote, array $counts): void
{
    $throttleFile = __DIR__ . '/notifications.json';
    $throttle     = loadData($throttleFile);

    if (time() - ($throttle[$slug] ?? 0) < NOTIFY_COOLDOWN_SECONDS) {
        return;
    }

    $articleUrl   = SITE_URL . '/' . $slug;
    $dashboardUrl = SITE_URL . '/reactions-dashboard';
    $total        = $counts['helpful'] + $counts['not_helpful'];
    $ratio        = $total > 0 ? round($counts['helpful'] / $total * 100) : 0;

    $subject = "[Blog] New reaction on: $slug";
    $body    = implode("\n", [
        "A reader just reacted to one of your blog posts.",
        "",
        "Article     : $articleUrl",
        "Vote        : $vote",
        "Helpful     : {$counts['helpful']}",
        "Not helpful : {$counts['not_helpful']}",
        "Approval    : {$ratio}%",
        "",
        "View full dashboard: $dashboardUrl",
    ]);
    $headers = implode("\r\n", [
        "From: " . NO_REPLY,
        "Reply-To: " . NO_REPLY,
        "Content-Type: text/plain; charset=utf-8",
    ]);

    if (@mail(ADMIN_EMAIL, $subject, $body, $headers)) {
        $throttle[$slug] = time();
        saveData($throttleFile, $throttle);
    }
}

// ── Parse input ───────────────────────────────────────────────────────────────

$method = $_SERVER['REQUEST_METHOD'];
$slug   = '';
$vote   = '';

if ($method === 'GET') {
    // Admin request: return all reaction data
    if (array_key_exists('admin', $_GET)) {
        if (ADMIN_TOKEN === '' || ($_GET['admin'] ?? '') !== ADMIN_TOKEN) {
            jsonError(403, 'Forbidden');
        }
        echo json_encode(loadData(__DIR__ . '/reactions-data.json'));
        exit;
    }
    $slug = sanitizeSlug($_GET['slug'] ?? '');
} elseif ($method === 'POST') {
    $body = json_decode(file_get_contents('php://input'), true) ?? [];
    $slug = sanitizeSlug($body['slug'] ?? '');
    $vote = $body['vote'] ?? '';
} else {
    jsonError(405, 'Method not allowed');
}

if ($slug === '') {
    jsonError(400, 'Missing slug');
}

// ── Load data ─────────────────────────────────────────────────────────────────

$dataFile = __DIR__ . '/reactions-data.json';
$data     = loadData($dataFile);

if (!isset($data[$slug])) {
    $data[$slug] = ['helpful' => 0, 'not_helpful' => 0];
}

// ── Record vote ───────────────────────────────────────────────────────────────

if ($method === 'POST') {
    if ($vote === 'helpful') {
        $data[$slug]['helpful']++;
    } elseif ($vote === 'not_helpful') {
        $data[$slug]['not_helpful']++;
    } else {
        jsonError(400, 'Invalid vote value');
    }
    saveData($dataFile, $data);
    maybeNotify($slug, $vote, $data[$slug]);
}

echo json_encode($data[$slug]);
```

Four constants, four decisions to make:

* **`ADMIN_EMAIL`** — where email notifications go. Use your own address.
* **`ADMIN_TOKEN`** — a long random string (32+ characters). This protects the admin endpoint that returns all votes. Generate one with `openssl rand -base64 24` in your terminal and never commit it to a public repository.
* **`NOREPLY`** — your noreply email address.
* **`NOTIFY_COOLDOWN_SECONDS`** — the minimum number of seconds between two notification emails *for the same article*. The default is 3 600 (one hour). This prevents your inbox from being flooded when an article goes viral.
* **`SITE_URL`** — your public domain, used to build clickable links in the notification email and to validate CORS origins. **Think to change this value to yours.**

> **Using a .env file:**
>
> Don't hardcode your email, token, ... in the PHP file. Add the `api/.env` file next to the `reactions.php` file and replace placeholders by your own values.
>
> **api/.env**
>
> ```
> ADMIN_EMAIL=your_email@your_domain
> ADMIN_TOKEN=change-me-to-a-long-random-string
> NO_REPLY=noreply@your_domain
> IP_HASH_SALT=change-me-to-another-long-random-string
> NONCE_SECRET=change-me-to-yet-another-long-random-string
> ```

### 1.2 — CORS

A word about CORS: in this `api/reactions.php` file, you'll find this snippet:

```php title="api/reactions.php"
$allowedOrigins = [
    SITE_URL,
    'https://localhost:3000',
];

$origin = $_SERVER['HTTP_ORIGIN'] ?? '';
if (!in_array($origin, $allowedOrigins, true)) {
    http_response_code(403);
    exit;
}

header('Content-Type: application/json; charset=utf-8');
header("Access-Control-Allow-Origin: $origin");
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
header('Vary: Origin');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(204);
    exit;
}
```

The CORS block does two things.

First, it rejects any request that does not originate from your site or from `localhost:3000` (your local Docusaurus dev server). Without this check, anyone could POST fake votes from any origin. The check is strict (`in_array` with the third argument `true`): no substring matching, no wildcards.

Second, it echoes the validated origin back in the `Access-Control-Allow-Origin` header. This is more correct than the wildcard `*` approach because it works with credentials and explicitly tells browsers which origin is allowed — and the `Vary: Origin` header ensures that caches respect per-origin responses.

The `OPTIONS` branch handles the browser preflight that precedes any cross-origin POST with a `Content-Type: application/json` header.

> **Why localhost:3000?:**
>
> During development, `yarn start` serves Docusaurus on `https://localhost:3000`. Without adding it to the allowed origins list, every vote from your dev environment would be silently rejected by the browser before even reaching the server.

### 1.3 — Email notification with per-article throttling

A word about email notification: in this `api/reactions.php` file, you'll find this snippet:

```php title="api/reactions.php"
function maybeNotify(string $slug, string $vote, array $counts): void
{
    $throttleFile = __DIR__ . '/notifications.json';
    $throttle     = loadData($throttleFile);

    if (time() - ($throttle[$slug] ?? 0) < NOTIFY_COOLDOWN_SECONDS) {
        return;
    }

    $articleUrl   = SITE_URL . '/' . $slug;
    $dashboardUrl = SITE_URL . '/reactions-dashboard';
    $total        = $counts['helpful'] + $counts['not_helpful'];
    $ratio        = $total > 0 ? round($counts['helpful'] / $total * 100) : 0;

    $subject = "[Blog] New reaction on: $slug";
    $body    = implode("\n", [
        "A reader just reacted to one of your blog posts.",
        "",
        "Article     : $articleUrl",
        "Vote        : $vote",
        "Helpful     : {$counts['helpful']}",
        "Not helpful : {$counts['not_helpful']}",
        "Approval    : {$ratio}%",
        "",
        "View full dashboard: $dashboardUrl",
    ]);

    $headers = implode("\r\n", [
        "From: " . NO_REPLY,
        "Reply-To: " . NO_REPLY,
        "Content-Type: text/plain; charset=utf-8",
    ]);

    if (@mail(ADMIN_EMAIL, $subject, $body, $headers)) {
        $throttle[$slug] = time();
        saveData($throttleFile, $throttle);
    }
}
```

The throttle check is the key line: `time() - ($throttle[$slug] ?? 0) < NOTIFY_COOLDOWN_SECONDS`. If the last email for this article was sent less than `NOTIFY_COOLDOWN_SECONDS` ago, the function returns immediately without sending anything. The throttle timestamp is only saved when `mail()` actually succeeds, so a failed send does not block the next attempt.

The notification email includes the vote type, the running totals, and the approval ratio — enough context to decide whether an article needs attention without having to open the dashboard.

> **Adjust the cooldown to your traffic:**
>
> On a low-traffic blog, a one-hour cooldown is reasonable. If you ever end up on a high-traffic aggregator, consider bumping `NOTIFY_COOLDOWN_SECONDS` to `86400` (24 hours) temporarily. The votes are never lost, you just receive fewer emails about them.

### 1.4 — Routing: GET and POST

```php title="api/reactions.php"
$method = $_SERVER['REQUEST_METHOD'];
$slug   = '';
$vote   = '';

if ($method === 'GET') {
    // Admin request: return all reaction data
    if (array_key_exists('admin', $_GET)) {
        if (($_GET['admin'] ?? '') !== ADMIN_TOKEN) {
            jsonError(403, 'Forbidden');
        }
        echo json_encode(loadData(__DIR__ . '/reactions-data.json'));
        exit;
    }
    $slug = sanitizeSlug($_GET['slug'] ?? '');
} elseif ($method === 'POST') {
    $body = json_decode(file_get_contents('php://input'), true) ?? [];
    $slug = sanitizeSlug($body['slug'] ?? '');
    $vote = $body['vote'] ?? '';
} else {
    jsonError(405, 'Method not allowed');
}

if ($slug === '') {
    jsonError(400, 'Missing slug');
}
```

The GET branch handles two cases.

When the `admin` query parameter is present, the script checks it against `ADMIN_TOKEN`. A matching token returns the full contents of `reactions-data.json` — the data consumed by the dashboard. A non-matching token returns a `403 Forbidden`.

When `admin` is absent, the script reads the `slug` query parameter. This is the public endpoint the React component calls on page load to get the current vote counts for a specific article.

The POST branch reads the request body as JSON (the React component sends `Content-Type: application/json`). It extracts `slug` and `vote`. Both go through validation in the next section.

```php title="api/reactions.php"
$dataFile = __DIR__ . '/reactions-data.json';
$data     = loadData($dataFile);

if (!isset($data[$slug])) {
    $data[$slug] = ['helpful' => 0, 'not_helpful' => 0];
}

if ($method === 'POST') {
    if ($vote === 'helpful') {
        $data[$slug]['helpful']++;
    } elseif ($vote === 'not_helpful') {
        $data[$slug]['not_helpful']++;
    } else {
        jsonError(400, 'Invalid vote value');
    }
    saveData($dataFile, $data);
    maybeNotify($slug, $vote, $data[$slug]);
}

echo json_encode($data[$slug]);
```

On first access, the slug entry is created with zeroed counters. The POST branch increments the right counter, saves the file, and triggers the throttled notification. Any `vote` value other than `helpful` or `not_helpful` is rejected immediately. The final line echoes the (updated or unchanged) counts for this slug, whatever the method.

***

## Step 2 — The React component

Create the folder `src/components/Reaction/` and the file `index.tsx` inside it.

**src/components/Reaction/index.tsx**

```typescript
import { useState, useEffect, useCallback, type JSX } from "react";
import useDocusaurusContext from "@docusaurus/useDocusaurusContext";
import useBaseUrl from "@docusaurus/useBaseUrl";
import styles from "./styles.module.css";
import Translate, { translate } from "@docusaurus/Translate";

interface Props {
  metadata?: {
    permalink?: string;
  };
}

interface Counts {
  helpful: number;
  not_helpful: number;
}

export default function Reaction({ metadata }: Props): JSX.Element | null {
  const { siteConfig } = useDocusaurusContext();
  const slug = metadata?.permalink?.replace(/^\/|\/$/g, "") ?? "";
  const apiUrl = `${siteConfig.url}/api/reactions.php`;
  const storageKey = `reaction_${slug}`;

  const mascotYesUrl = useBaseUrl("/img/reaction-mascot-yes.webp");
  const mascotNoUrl = useBaseUrl("/img/reaction-mascot-no.webp");

  const [counts, setCounts] = useState<Counts | null>(null);
  // null until the client-side effect runs — avoids SSR/hydration mismatch (#418).
  // If voted were read in useState(), SSR would produce null (no localStorage)
  // while the client would produce "helpful", causing a React tree mismatch.
  const [voted, setVoted] = useState<string | null>(null);
  const [submitError, setSubmitError] = useState(false);

  useEffect(() => {
    try {
      const stored = localStorage.getItem(storageKey);
      // eslint-disable-next-line react-hooks/set-state-in-effect -- intentional SSR/hydration-safe read, see comment on `voted` above
      if (stored) setVoted(stored);
    } catch {}
  }, [storageKey]);

  useEffect(() => {
    if (!slug) return;
    fetch(`${apiUrl}?slug=${encodeURIComponent(slug)}`)
      .then((r) => (r.ok ? r.json() : null))
      .then((data) => {
        if (data) setCounts(data);
      })
      .catch(() => {});
  }, [slug, apiUrl]);

  const handleVote = useCallback(
    async (vote: string) => {
      setSubmitError(false);
      try {
        const res = await fetch(apiUrl, {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ slug, vote }),
        });
        if (!res.ok) {
          setSubmitError(true);
          return;
        }
        const data = await res.json();
        setCounts(data);
        setVoted(vote);
        try {
          localStorage.setItem(storageKey, vote);
        } catch {}
      } catch {
        setSubmitError(true);
      }
    },
    [slug, apiUrl, storageKey],
  );

  if (!slug) return null;

  return (
    <div className={styles.container}>
      {!voted ? (
        <>
          <span className={styles.question}>
            <Translate id="blog.reaction.question">Was this article helpful?</Translate>
          </span>
          <div className={styles.buttons}>
            <button
              className={styles.btn}
              onClick={() => handleVote("helpful")}
              aria-label={translate({
                id: "blog.reaction.yes.ariaLabel",
                message: "Yes, this was helpful",
              })}
            >
              <img src={mascotYesUrl} alt="" className={styles.mascot} />
              <Translate id="blog.reaction.yes">Helpful</Translate>
            </button>
            <button
              className={`${styles.btn} ${styles.btnNeutral}`}
              onClick={() => handleVote("not_helpful")}
              aria-label={translate({
                id: "blog.reaction.no.ariaLabel",
                message: "No, this was not helpful",
              })}
            >
              <img src={mascotNoUrl} alt="" className={styles.mascot} />
              <Translate id="blog.reaction.no">Not really</Translate>
            </button>
          </div>
          {submitError && (
            <span className={styles.submitError}>
              <Translate id="reaction.saveError">
                Could not save your vote — please try again.
              </Translate>
            </span>
          )}
        </>
      ) : (
        <div className={styles.thanks}>
          <span className={styles.thanksMsg}>
            {voted === "helpful"
              ? translate({ id: "reaction.thanksHelpful", message: "Glad it helped! 🙌" })
              : translate({
                  id: "reaction.thanksNotHelpful",
                  message: "Thanks for the feedback!",
                })}
          </span>
          {counts && (
            <span className={styles.counts}>
              <span
                title={translate(
                  { id: "reaction.countHelpful", message: "{count} found this helpful" },
                  { count: counts.helpful },
                )}
              >
                👍 {counts.helpful}
              </span>
              <span
                title={translate(
                  {
                    id: "reaction.countNotHelpful",
                    message: "{count} did not find this helpful",
                  },
                  { count: counts.not_helpful },
                )}
              >
                👎 {counts.not_helpful}
              </span>
            </span>
          )}
        </div>
      )}
    </div>
  );
}
```

### 2.1 — Imports and setup

```tsx title="src/components/Reaction/index.tsx"
import { useState, useEffect, useCallback, type JSX } from "react";
import useDocusaurusContext from "@docusaurus/useDocusaurusContext";
import styles from "./styles.module.css";

interface Props {
  metadata?: {
    permalink?: string;
  };
}

interface Counts {
  helpful: number;
  not_helpful: number;
}

export default function Reaction({ metadata }: Props): JSX.Element | null {
  const { siteConfig } = useDocusaurusContext();
  const slug = metadata?.permalink?.replace(/^\/|\/$/g, "") ?? "";
  const apiUrl = `${siteConfig.url}/api/reactions.php`;
  const storageKey = `reaction_${slug}`;
```

`metadata` is the object that Docusaurus passes to every blog post component. We use `metadata.permalink` — the URL path of the article — as the slug. The two `replace` calls strip the leading and trailing slashes so, the slug matches what `sanitizeSlug` on the PHP side produces: `blog/my-article`, not `/blog/my-article/`.

The `Props` interface only needs `metadata.permalink`; everything else Docusaurus passes is ignored. `Counts` is the `{ helpful, not_helpful }` shape the PHP endpoint returns — reused below for the `counts` state.

`siteConfig.url` is your production URL from `docusaurus.config.js`. The component builds the API URL from it dynamically, which means it also works correctly in development (where `url` will point to `https://localhost:3000` if you configure it that way, but in practice the component is only mounted after Docusaurus resolves the site config).

`storageKey` gives every article its own entry in `localStorage` (`reaction_blog-my-article`), preventing a vote on one article from affecting another.

### 2.2 — State

```tsx title="src/components/Reaction/index.tsx"
  const [counts, setCounts] = useState<Counts | null>(null);
  const [voted, setVoted] = useState<string | null>(null);
  const [submitError, setSubmitError] = useState(false);

  useEffect(() => {
    try {
      const stored = localStorage.getItem(storageKey);
      if (stored) setVoted(stored);
    } catch {}
  }, [storageKey]);
```

`counts` holds the `{ helpful, not_helpful }` object returned by the API. It starts as `null` (not yet loaded). `submitError` is a flag flipped on when a vote POST fails, so the render can show a retry message.

`voted` holds the previous vote for this article. It starts as `null` and is only populated **after mount**, inside a `useEffect` that reads `localStorage`. The `try/catch` is there because `localStorage` can throw in private browsing modes or when storage is full.

> **Why not read localStorage in useState?:**
>
> Docusaurus server-renders every page. If `voted` were seeded from `localStorage` in a `useState` initializer, the server would produce `null` (no `localStorage` there) while the browser would produce the stored `"helpful"` — the two HTML trees disagree, and React throws a hydration mismatch. Deferring the read to `useEffect` keeps the first client render identical to the server's, then updates. Anything outside `useState`, `useEffect`, or an event handler still needs a `typeof window !== "undefined"` guard.

### 2.3 — Loading counts on mount

```tsx title="src/components/Reaction/index.tsx"
  useEffect(() => {
    if (!slug) return;
    fetch(`${apiUrl}?slug=${encodeURIComponent(slug)}`)
      .then((r) => (r.ok ? r.json() : null))
      .then((data) => {
        if (data) setCounts(data);
      })
      .catch(() => {});
  }, [slug, apiUrl]);
```

On mount, the component fetches the current counts for this article. The `encodeURIComponent` call ensures the slug is safe in a URL query string. If the fetch fails for any reason (network error, server down, non-OK status), the error is swallowed silently — the widget simply stays in its initial state, which is fine.

### 2.4 — Sending a vote

```tsx title="src/components/Reaction/index.tsx"
  const handleVote = useCallback(
    async (vote: string) => {
      setSubmitError(false);
      try {
        const res = await fetch(apiUrl, {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ slug, vote }),
        });
        if (!res.ok) {
          setSubmitError(true);
          return;
        }
        const data = await res.json();
        setCounts(data);
        setVoted(vote);
        try {
          localStorage.setItem(storageKey, vote);
        } catch {}
      } catch {
        setSubmitError(true);
      }
    },
    [slug, apiUrl, storageKey],
  );
```

`handleVote` POSTs `{ slug, vote }` as JSON. On success, it updates the displayed counts with the fresh values returned by the server, sets `voted` to the chosen value (switching the UI from "vote buttons" to "thank you" state), and saves the vote to `localStorage`. Any failure — a non-OK response or a thrown `fetch` — sets `submitError`, which surfaces the retry message in the render below; `localStorage` write failures are swallowed since the vote itself already went through.

`useCallback` memoizes the function so it does not get recreated on every render, which is important since it is passed as an `onClick` prop.

### 2.5 — Rendering

```tsx title="src/components/Reaction/index.tsx"
  if (!slug) return null;

  return (
    <div className={styles.container}>
      {!voted ? (
        <>
          <span className={styles.question}>Was this article helpful?</span>
          <div className={styles.buttons}>
            <button
              className={styles.btn}
              onClick={() => handleVote("helpful")}
              aria-label="Yes, this was helpful"
            >
              👍 Helpful
            </button>
            <button
              className={`${styles.btn} ${styles.btnNeutral}`}
              onClick={() => handleVote("not_helpful")}
              aria-label="No, this was not helpful"
            >
              👎 Not really
            </button>
          </div>
          {submitError && (
            <span className={styles.submitError}>
              Could not save your vote — please try again.
            </span>
          )}
        </>
      ) : (
        <div className={styles.thanks}>
          <span className={styles.thanksMsg}>
            {voted === "helpful" ? "Glad it helped! 🙌" : "Thanks for the feedback!"}
          </span>
          {counts && (
            <span className={styles.counts}>
              <span title={`${counts.helpful} found this helpful`}>
                👍 {counts.helpful}
              </span>
              <span title={`${counts.not_helpful} did not find this helpful`}>
                👎 {counts.not_helpful}
              </span>
            </span>
          )}
        </div>
      )}
    </div>
  );
}
```

The rendering has two states. Before voting (`!voted`): the question, two buttons, and — only when `submitError` is set — a retry message under them. After voting (`voted` is set): a thank-you message personalized to the vote choice, plus the vote counts — which are now visible since the reader has expressed their opinion.

The `aria-label` attributes make the buttons accessible to screen readers: emoji-only labels like "👍 Helpful" are not always read correctly by screen readers, so an explicit label helps.

The `Props` and `Counts` interfaces at the top are the whole contract: the compiler flags a wrong `metadata` shape or a misused count field at build time, so there is no runtime `PropTypes` check to add.

***

## Step 3 — The CSS module

Create file `styles.module.css` in `src/components/Reaction/`.

**src/components/Reaction/styles.module.css**

```css
/*
 * ⚠️ DUPLICATION — Reaction/styles.module.css and TriedIt/styles.module.css are
 * the SAME FILE, byte for byte, except that Reaction adds .submitError. Two
 * components, one widget: a question, a row of buttons, a thank-you state and
 * a count. They were tokenised identically here so they stay in step, but the
 * real fix is to have one of them import the other's stylesheet (CSS modules
 * support `composes: … from "../Reaction/styles.module.css"`), or to extract a
 * shared Feedback component. Flagged, not done: that is a refactor decision,
 * not a styling one.
 *
 * Fixed while tokenising: the hover filled the button with solid primary and
 * set `color: white` — a literal, and the only white text on terracotta in
 * this part of the site. It now uses --mk-on-line, which flips with the theme
 * (in dark mode the primary lightens, so white-on-it fails contrast).
 */

.container {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 0.75rem;
  padding: 0.9rem 1.25rem;
  margin: 1.5rem 0 0.5rem;
  border: 1px solid var(--mk-border);
  border-radius: var(--mk-radius-md);
  background: var(--mk-surface);
  box-shadow: var(--mk-shadow-1);
}

.question {
  font-weight: 600;
  color: var(--mk-ink);
  white-space: nowrap;
}

.buttons {
  display: flex;
  gap: 0.5rem;
  flex-wrap: wrap;
}

.btn {
  display: inline-flex;
  align-items: center;
  gap: 0.35rem;
  padding: 0.35rem 0.85rem;
  font-family: inherit;
  border: 1px solid var(--mk-border-strong);
  border-radius: var(--mk-radius-sm);
  background: transparent;
  color: var(--mk-ink);
  font-size: 0.875rem;
  cursor: pointer;
  transition:
    background-color 0.15s ease,
    border-color 0.15s ease,
    color 0.15s ease;
}

.mascot {
  width: 1.5rem;
  height: 1.5rem;
  object-fit: contain;
}

.btn:hover {
  background-color: var(--mk-primary);
  border-color: var(--mk-primary);
  color: var(--mk-on-line);
}

.btn:focus-visible {
  outline: 2px solid var(--mk-primary);
  outline-offset: 2px;
}

.btnNeutral:hover {
  background-color: var(--mk-n-300);
  border-color: var(--mk-n-300);
  color: var(--mk-n-900);
}

.thanks {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 1rem;
}

.thanksMsg {
  font-weight: 600;
  color: var(--mk-ink);
}

.counts {
  display: flex;
  gap: 0.75rem;
  font-size: 0.875rem;
  color: var(--mk-ink-soft);
  font-variant-numeric: tabular-nums;
}

.submitError {
  font-size: 0.8rem;
  color: var(--mk-danger-line);
  width: 100%;
}
```

The outer `container` is a flex row with wrapping, so it collapses gracefully on narrow screens. The colors use Docusaurus CSS custom properties (`--ifm-*`), which means the widget automatically adapts to light mode, dark mode, and any custom Docusaurus theme without writing a single media query or duplicate rule.

The "Helpful" button turns the primary theme color on hover; the "Not really" button turns a neutral grey. The 0.15 s transition makes the hover feel responsive without being flashy.

***

## Step 4 — Injecting the widget via swizzling

**Swizzling** is Docusaurus's mechanism for replacing a built-in theme component with your own version. We want to inject `<Reaction />` at the bottom of every blog post page — and the right place to do that is `BlogPostItem`, the component that wraps the content and footer of every post.

### 4.1 — Run the swizzle command

```bash
yarn run swizzle @docusaurus/theme-classic BlogPostItem --wrap
```

> **Wrap vs. Eject:**
>
> The `--wrap` flag creates a thin wrapper around the original component rather than copying the entire source. However, for `BlogPostItem` we want fine-grained control over the layout (to place `<Reaction />` exactly where we want it, between the content and the footer). In practice, you will likely eject, not wrap. Run the command without `--wrap` and Docusaurus will ask you to confirm; choose **Eject**.

This creates `src/theme/BlogPostItem/index.js` with the original source. Open it.

### 4.2 — Modify the swizzled file

You need to make three changes: import the component, detect whether we are on a single-post page, and render `<Reaction />` conditionally.

Here is the relevant portion:

```javascript title="src/theme/BlogPostItem/index.js" {1,8,17-23}
import Reaction from "@site/src/components/Reaction";
import { useBlogPost } from "@docusaurus/plugin-content-blog/client";
import BlogPostItemContainer from "@theme/BlogPostItem/Container";
import BlogPostItemContent from "@theme/BlogPostItem/Content";
import BlogPostItemFooter from "@theme/BlogPostItem/Footer";
import BlogPostItemHeader from "@theme/BlogPostItem/Header";

function useContainerClassName() {
  const { isBlogPostPage } = useBlogPost();
  return !isBlogPostPage ? "margin-bottom--xl" : undefined;
}

export default function BlogPostItem({ children, className }) {
  const { metadata, isBlogPostPage } = useBlogPost();
  const containerClassName = useContainerClassName();

  return (
    <BlogPostItemContainer className={clsx(containerClassName, className)}>
      <BlogPostItemHeader />
      <BlogPostItemContent>{children}</BlogPostItemContent>
      <BlogPostItemFooter />

      {isBlogPostPage && (
        <Reaction metadata={metadata} />
      )}
    </BlogPostItemContainer>
  );
}
```

The key guard is `isBlogPostPage`. Docusaurus renders `BlogPostItem` in two contexts:

1. **Blog list pages** — where article cards are shown in a grid or feed.
2. **Single post pages** — where the full article is displayed.

Without the guard, a reaction widget would appear under every article card on the blog homepage, which is not what we want. `isBlogPostPage` is `true` only when you are reading a single post, so the widget shows up in exactly the right place.

> **Placement matters:**
>
> If you have other custom components (a Bluesky share button, [related posts](/blog/docusaurus-relatedposts), etc.), the order here defines the visual order at the bottom of every post. Adjust to your preference.

### 4.3 — The complete swizzled file ON MY SITE

> **:**
>
> Below is the contents of the index.js file on my blog. I'm sharing it as an example and for comparison, since I use many more React components than just the one we just covered in this post.

**src/theme/BlogPostItem/index.js**

```javascript
import ArticleActions from "@site/src/components/Blog/ArticleActions";
import PropTypes from "prop-types";
import { useBlogPost } from "@docusaurus/plugin-content-blog/client";
import BlogPostItemContainer from "@theme/BlogPostItem/Container";
import BlogPostItemContent from "@theme/BlogPostItem/Content";
import BlogPostItemFooter from "@theme/BlogPostItem/Footer";
import BlogPostItemHeader from "@theme/BlogPostItem/Header";
import Reaction from "@site/src/components/Reaction";
import TriedIt from "@site/src/components/TriedIt";
import TypoReport from "@site/src/components/TypoReport";
import clsx from "clsx";

// Our posts components
import RelatedPosts from "@site/src/components/Blog/RelatedPosts";

// Locale awareness — both render nothing on the English site unless a translation exists.
import TranslationNotice from "@site/src/components/Blog/TranslationNotice";

// Our Bluesky component
import Bluesky from "@site/src/components/Bluesky";

// apply a bottom margin in list view
function useContainerClassName() {
  const { isBlogPostPage } = useBlogPost();
  return !isBlogPostPage ? "margin-bottom--xl" : undefined;
}
export default function BlogPostItem({ children, className }) {
  // We need to retrieve the isBlogPostPage flag
  const { metadata, isBlogPostPage } = useBlogPost();
  const { frontMatter } = metadata;
  const containerClassName = useContainerClassName();
  // These actions only make sense for the article the reader is actually on,
  // never for a card in a list view.
  const actions = isBlogPostPage ? <ArticleActions metadata={metadata} /> : null;

  return (
    <>
      <BlogPostItemContainer className={clsx(containerClassName, className)}>
        <BlogPostItemHeader actions={actions} />
        {/* Above the content, never inside the translated Markdown file: the banner must not be
            something the translator can mangle, and the flag must be reachable before the
            reader has scrolled through prose they may not want to read. */}
        {/* The flag badge used to sit here too. Removed on 2026-09-16: the sentence below says
            the same thing in words, and a badge that duplicates it is noise at the very place a
            reader is trying to start the article. */}
        {isBlogPostPage && <TranslationNotice permalink={metadata.permalink} />}
        <BlogPostItemContent>{children}</BlogPostItemContent>
        <BlogPostItemFooter />

        {/* Only display our RelatedPosts and Bluesky components on the post page; not the blog view */}
        {isBlogPostPage && (
          <>
            <TypoReport metadata={metadata} />
            <Reaction metadata={metadata} />
            {frontMatter.tried_it !== false && <TriedIt metadata={metadata} />}
            {/* Bluesky comes first: it and RelatedPosts are both exit points
                (off-site vs. another post), and whichever renders first wins
                the click of a reader who just finished and is ready to act.
                Bluesky engagement is the current priority ask. */}
            <Bluesky metadata={metadata} />
            {/* Readers who reach the end of an article should meet the next one
                to read before the reaction, comment and typo report blocks.
                Buried under those widgets, these links were never seen. */}
            <RelatedPosts count={6} description={true} />
          </>
        )}
      </BlogPostItemContainer>
    </>
  );
}
BlogPostItem.propTypes = {
  children: PropTypes.node,
  className: PropTypes.string,
};
```

***

## Step 5 — The admin dashboard

The dashboard is a standard Docusaurus page (not a blog post) that calls the admin endpoint of `reactions.php` and presents the data in a table with per-article approval bars.

Create `src/pages/reactions-dashboard.js` with this content:

**src/pages/reactions-dashboard.js**

```javascript
import { useState, useEffect, useCallback } from "react";
import PropTypes from "prop-types";
import Layout from "@theme/Layout";
import Head from "@docusaurus/Head";
import useDocusaurusContext from "@docusaurus/useDocusaurusContext";
import styles from "./reactions-dashboard.module.css";

// ── Data helpers ─────────────────────────────────────────────────────────────

function computeTotals(data) {
  let totalHelpful = 0;
  let totalNot = 0;

  const rows = Object.entries(data)
    .map(([slug, counts]) => {
      const helpful = counts.helpful ?? 0;
      const notHelpful = counts.not_helpful ?? 0;
      const total = helpful + notHelpful;
      const ratio = total > 0 ? Math.round((helpful / total) * 100) : 0;
      totalHelpful += helpful;
      totalNot += notHelpful;
      return { slug, helpful, notHelpful, total, ratio };
    })
    .sort((a, b) => b.helpful - a.helpful || b.total - a.total);

  const grandTotal = totalHelpful + totalNot;
  const approval = grandTotal > 0 ? Math.round((totalHelpful / grandTotal) * 100) : 0;

  return { rows, totalHelpful, totalNot, grandTotal, approval };
}

// ── Sub-components ───────────────────────────────────────────────────────────

function SummaryCards({ totalHelpful, totalNot, grandTotal, approval }) {
  return (
    <div className={styles.summary}>
      <div className={styles.card}>
        <div className={styles.cardValue}>{grandTotal}</div>
        <div className={styles.cardLabel}>Total votes</div>
      </div>
      <div className={styles.card}>
        <div className={styles.cardValue}>👍 {totalHelpful}</div>
        <div className={styles.cardLabel}>Helpful</div>
      </div>
      <div className={styles.card}>
        <div className={styles.cardValue}>👎 {totalNot}</div>
        <div className={styles.cardLabel}>Not helpful</div>
      </div>
      <div className={styles.card}>
        <div className={styles.cardValue}>{approval}%</div>
        <div className={styles.cardLabel}>Approval rate</div>
      </div>
    </div>
  );
}

SummaryCards.propTypes = {
  totalHelpful: PropTypes.number.isRequired,
  totalNot: PropTypes.number.isRequired,
  grandTotal: PropTypes.number.isRequired,
  approval: PropTypes.number.isRequired,
};

function ApprovalBar({ ratio }) {
  return (
    <div className={styles.barWrap}>
      <div className={styles.bar}>
        <div className={styles.barFill} style={{ width: `${ratio}%` }} />
      </div>
      <span className={styles.barLabel}>{ratio}%</span>
    </div>
  );
}

ApprovalBar.propTypes = {
  ratio: PropTypes.number.isRequired,
};

function ReactionsTable({ rows, siteUrl }) {
  if (rows.length === 0) {
    return <p className={styles.empty}>No reactions recorded yet.</p>;
  }

  return (
    <table className={styles.table}>
      <thead>
        <tr>
          <th>Article</th>
          <th className={styles.right}>👍</th>
          <th className={styles.right}>👎</th>
          <th className={styles.right}>Total</th>
          <th>Approval</th>
        </tr>
      </thead>
      <tbody>
        {rows.map(({ slug, helpful, notHelpful, total, ratio }) => (
          <tr key={slug}>
            <td>
              <a
                href={`${siteUrl}/${slug}`}
                target="_blank"
                rel="noopener noreferrer"
                className={styles.articleLink}
              >
                {slug}
              </a>
            </td>
            <td className={styles.right}>{helpful}</td>
            <td className={styles.right}>{notHelpful}</td>
            <td className={styles.right}>{total}</td>
            <td>
              <ApprovalBar ratio={ratio} />
            </td>
          </tr>
        ))}
      </tbody>
    </table>
  );
}

ReactionsTable.propTypes = {
  rows: PropTypes.arrayOf(
    PropTypes.shape({
      slug: PropTypes.string.isRequired,
      helpful: PropTypes.number.isRequired,
      notHelpful: PropTypes.number.isRequired,
      total: PropTypes.number.isRequired,
      ratio: PropTypes.number.isRequired,
    }),
  ).isRequired,
  siteUrl: PropTypes.string.isRequired,
};

function AuthForm({ onSubmit }) {
  const [token, setToken] = useState("");

  return (
    <div className={styles.authWrap}>
      <p>Enter your admin token to view the dashboard.</p>
      <form
        className={styles.authForm}
        onSubmit={(e) => {
          e.preventDefault();
          onSubmit(token.trim());
        }}
      >
        <input
          className={styles.authInput}
          type="password"
          placeholder="Admin token"
          value={token}
          onChange={(e) => setToken(e.target.value)}
          autoFocus
        />
        <button className={styles.authBtn} type="submit">
          View
        </button>
      </form>
    </div>
  );
}

AuthForm.propTypes = {
  onSubmit: PropTypes.func.isRequired,
};

const STORAGE_KEY = "reactions_admin_token";

// ── Page ─────────────────────────────────────────────────────────────────────

export default function ReactionsDashboard() {
  const { siteConfig } = useDocusaurusContext();
  const apiUrl = `${siteConfig.url}/api/reactions.php`;

  const [token, setToken] = useState("");
  const [data, setData] = useState(null);
  const [error, setError] = useState(null);
  const [loading, setLoading] = useState(false);

  // Priority: URL hash → localStorage → empty (show form).
  // Must run in useEffect — localStorage is unavailable during SSR,
  // and React does not re-run useState initializers on client hydration.
  useEffect(() => {
    const initial =
      window.location.hash.slice(1) || localStorage.getItem(STORAGE_KEY) || "";
    // eslint-disable-next-line react-hooks/set-state-in-effect -- intentional SSR/hydration-safe read, see comment above
    if (initial) setToken(initial);
  }, []);

  const fetchData = useCallback(
    async (t) => {
      if (!t) return;
      setLoading(true);
      setError(null);
      try {
        const res = await fetch(`${apiUrl}?admin=${encodeURIComponent(t)}`);
        if (res.status === 403) {
          localStorage.removeItem(STORAGE_KEY);
          setError("Invalid token.");
          setData(null);
          return;
        }
        if (!res.ok) throw new Error(`HTTP ${res.status}`);
        localStorage.setItem(STORAGE_KEY, t);
        setData(await res.json());
      } catch (e) {
        setError(`Failed to load data: ${e.message}`);
        setData(null);
      } finally {
        setLoading(false);
      }
    },
    [apiUrl],
  );

  // Reactive sync: refetch whenever the token changes (login, restore from storage, hash link).
  useEffect(() => {
    // eslint-disable-next-line react-hooks/set-state-in-effect -- fetchData sets state, but this is a legitimate reaction to `token` changing, not derivable at render time
    if (token) fetchData(token);
  }, [token, fetchData]);

  const handleTokenSubmit = (t) => {
    setToken(t);
    fetchData(t);
  };

  const handleForget = () => {
    localStorage.removeItem(STORAGE_KEY);
    setToken("");
    setData(null);
    setError(null);
  };

  const stats = data ? computeTotals(data) : null;

  return (
    <Layout title="Reactions Dashboard" noFooter>
      <Head>
        <meta name="robots" content="noindex, nofollow" />
      </Head>

      <div className={styles.page}>
        <div className={styles.header}>
          <h1>Reactions Dashboard</h1>
          <p className={styles.subtitle}>
            Per-article reader feedback — sorted by helpful count
          </p>
        </div>

        {!token && <AuthForm onSubmit={handleTokenSubmit} />}

        {token && loading && <p>Loading…</p>}

        {token && error && <p className={styles.error}>{error}</p>}

        {stats && (
          <>
            <SummaryCards {...stats} />
            <ReactionsTable rows={stats.rows} siteUrl={siteConfig.url} />
            <button className={styles.forgetBtn} onClick={handleForget}>
              Forget token
            </button>
          </>
        )}
      </div>
    </Layout>
  );
}
```

### 5.1 — Authentication

The page reads the admin token from the URL hash (`/reactions-dashboard#your-token`). If no hash is present, it renders an input form to enter the token manually. The token is never sent in the URL path or stored in `localStorage`.

```javascript title="src/pages/reactions-dashboard.js"
const [token, setToken] = useState(() => {
  if (typeof window === "undefined") return "";
  return window.location.hash.slice(1);
});
```

Passing the token in the hash is a practical choice: the hash is never sent to the server in the HTTP request, so it does not appear in server logs, and you can bookmark the URL.

Fill your `ADMIN_TOKEN` to connect:

> Screenshot — https\://www\.avonture.be/reactions-dashboard/
>
> The reaction dashboard login page

### 5.2 — Data loading

```javascript title="src/pages/reactions-dashboard.js"
const fetchData = useCallback(async (t) => {
  if (!t) return;
  setLoading(true);
  setError(null);
  try {
    const res = await fetch(`${apiUrl}?admin=${encodeURIComponent(t)}`);
    if (res.status === 403) { setError("Invalid token."); setData(null); return; }
    if (!res.ok) throw new Error(`HTTP ${res.status}`);
    setData(await res.json());
  } catch (e) {
    setError(`Failed to load data: ${e.message}`);
    setData(null);
  } finally {
    setLoading(false);
  }
}, [apiUrl]);
```

A `403` means the token is wrong and gets a clear "Invalid token." message. Any other non-OK status is treated as a generic error. The `finally` block always clears the loading state.

### 5.3 — Aggregation

```javascript title="src/pages/reactions-dashboard.js"
function computeTotals(data) {
  let totalHelpful = 0;
  let totalNot = 0;

  const rows = Object.entries(data)
    .map(([slug, counts]) => {
      const helpful    = counts.helpful    ?? 0;
      const notHelpful = counts.not_helpful ?? 0;
      const total      = helpful + notHelpful;
      const ratio      = total > 0 ? Math.round((helpful / total) * 100) : 0;
      totalHelpful += helpful;
      totalNot     += notHelpful;
      return { slug, helpful, notHelpful, total, ratio };
    })
    .sort((a, b) => b.helpful - a.helpful || b.total - a.total);

  const grandTotal = totalHelpful + totalNot;
  const approval   = grandTotal > 0 ? Math.round((totalHelpful / grandTotal) * 100) : 0;

  return { rows, totalHelpful, totalNot, grandTotal, approval };
}
```

`computeTotals` iterates over every article in `reactions-data.json`, computes a per-article approval ratio, and sorts by helpful count descending (ties broken by total votes). The grand totals at the end power the summary cards at the top of the page.

And here is what you can get:

> Screenshot — https\://www\.avonture.be/reactions-dashboard/
>
> The reaction dashboard

***

## All Files at a Glance

Here is the full set of files involved, grouped for easy installation (rendered with my [code snippets component](/blog/docusaurus-snippets)).

> **... excluding src/theme/BlogPostItem/index.js:**
>
> In the list below, I've not included `src/theme/BlogPostItem/index.js` because, as said, that file will vary between my blog and yours. Please refer to **Step 4** and create the file manually.

**Project: Reaction widget**

**api/.env**

```
ADMIN_EMAIL=your_email@your_domain
ADMIN_TOKEN=change-me-to-a-long-random-string
NO_REPLY=noreply@your_domain
IP_HASH_SALT=change-me-to-another-long-random-string
NONCE_SECRET=change-me-to-yet-another-long-random-string
```

**api/reactions.php**

```php
<?php
declare(strict_types=1);

// ── Configuration ─────────────────────────────────────────────────────────────
// Copy api/.env.example to api/.env and set your values before deploying.
$_envVars = file_exists(__DIR__ . '/.env')
    ? (parse_ini_file(__DIR__ . '/.env') ?: [])
    : [];

define('ADMIN_EMAIL',            $_envVars['ADMIN_EMAIL'] ?? '');
define('ADMIN_TOKEN',            $_envVars['ADMIN_TOKEN'] ?? '');
define('NO_REPLY',               $_envVars['NO_REPLY'] ?? '');
define('NOTIFY_COOLDOWN_SECONDS', 3600);   // minimum gap between emails per article
define('SITE_URL',               'https://www.avonture.be');

// ── CORS ──────────────────────────────────────────────────────────────────────
$allowedOrigins = [
    SITE_URL,
    'https://localhost:3000',
];

// Same-origin requests carry no Origin header — allow them unconditionally.
// Only cross-origin requests need to be validated.
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';
if ($origin !== '' && !in_array($origin, $allowedOrigins, true)) {
    http_response_code(403);
    exit;
}

header('Content-Type: application/json; charset=utf-8');
if ($origin !== '') {
    header("Access-Control-Allow-Origin: $origin");
    header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
    header('Access-Control-Allow-Headers: Content-Type');
    header('Vary: Origin');
}

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(204);
    exit;
}

// ── Helpers ───────────────────────────────────────────────────────────────────

function loadData(string $file): array
{
    if (!file_exists($file)) {
        return [];
    }
    return json_decode(file_get_contents($file), true) ?: [];
}

function saveData(string $file, array $data): void
{
    $fp = fopen($file, 'c+');
    if (!$fp) {
        return;
    }
    if (flock($fp, LOCK_EX)) {
        ftruncate($fp, 0);
        rewind($fp);
        fwrite($fp, json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
        flock($fp, LOCK_UN);
    }
    fclose($fp);
}

function sanitizeSlug(string $raw): string
{
    $slug = preg_replace('/[^a-z0-9\-\/]/', '', strtolower(trim($raw)));
    return substr($slug, 0, 200);
}

function jsonError(int $code, string $message): never
{
    http_response_code($code);
    echo json_encode(['error' => $message]);
    exit;
}

// Sends an email notification for a new vote, with a per-article cooldown.
function maybeNotify(string $slug, string $vote, array $counts): void
{
    $throttleFile = __DIR__ . '/notifications.json';
    $throttle     = loadData($throttleFile);

    if (time() - ($throttle[$slug] ?? 0) < NOTIFY_COOLDOWN_SECONDS) {
        return;
    }

    $articleUrl   = SITE_URL . '/' . $slug;
    $dashboardUrl = SITE_URL . '/reactions-dashboard';
    $total        = $counts['helpful'] + $counts['not_helpful'];
    $ratio        = $total > 0 ? round($counts['helpful'] / $total * 100) : 0;

    $subject = "[Blog] New reaction on: $slug";
    $body    = implode("\n", [
        "A reader just reacted to one of your blog posts.",
        "",
        "Article     : $articleUrl",
        "Vote        : $vote",
        "Helpful     : {$counts['helpful']}",
        "Not helpful : {$counts['not_helpful']}",
        "Approval    : {$ratio}%",
        "",
        "View full dashboard: $dashboardUrl",
    ]);
    $headers = implode("\r\n", [
        "From: " . NO_REPLY,
        "Reply-To: " . NO_REPLY,
        "Content-Type: text/plain; charset=utf-8",
    ]);

    if (@mail(ADMIN_EMAIL, $subject, $body, $headers)) {
        $throttle[$slug] = time();
        saveData($throttleFile, $throttle);
    }
}

// ── Parse input ───────────────────────────────────────────────────────────────

$method = $_SERVER['REQUEST_METHOD'];
$slug   = '';
$vote   = '';

if ($method === 'GET') {
    // Admin request: return all reaction data
    if (array_key_exists('admin', $_GET)) {
        if (ADMIN_TOKEN === '' || ($_GET['admin'] ?? '') !== ADMIN_TOKEN) {
            jsonError(403, 'Forbidden');
        }
        echo json_encode(loadData(__DIR__ . '/reactions-data.json'));
        exit;
    }
    $slug = sanitizeSlug($_GET['slug'] ?? '');
} elseif ($method === 'POST') {
    $body = json_decode(file_get_contents('php://input'), true) ?? [];
    $slug = sanitizeSlug($body['slug'] ?? '');
    $vote = $body['vote'] ?? '';
} else {
    jsonError(405, 'Method not allowed');
}

if ($slug === '') {
    jsonError(400, 'Missing slug');
}

// ── Load data ─────────────────────────────────────────────────────────────────

$dataFile = __DIR__ . '/reactions-data.json';
$data     = loadData($dataFile);

if (!isset($data[$slug])) {
    $data[$slug] = ['helpful' => 0, 'not_helpful' => 0];
}

// ── Record vote ───────────────────────────────────────────────────────────────

if ($method === 'POST') {
    if ($vote === 'helpful') {
        $data[$slug]['helpful']++;
    } elseif ($vote === 'not_helpful') {
        $data[$slug]['not_helpful']++;
    } else {
        jsonError(400, 'Invalid vote value');
    }
    saveData($dataFile, $data);
    maybeNotify($slug, $vote, $data[$slug]);
}

echo json_encode($data[$slug]);
```

**src/components/Reaction/index.tsx**

```typescript
import { useState, useEffect, useCallback, type JSX } from "react";
import useDocusaurusContext from "@docusaurus/useDocusaurusContext";
import useBaseUrl from "@docusaurus/useBaseUrl";
import styles from "./styles.module.css";
import Translate, { translate } from "@docusaurus/Translate";

interface Props {
  metadata?: {
    permalink?: string;
  };
}

interface Counts {
  helpful: number;
  not_helpful: number;
}

export default function Reaction({ metadata }: Props): JSX.Element | null {
  const { siteConfig } = useDocusaurusContext();
  const slug = metadata?.permalink?.replace(/^\/|\/$/g, "") ?? "";
  const apiUrl = `${siteConfig.url}/api/reactions.php`;
  const storageKey = `reaction_${slug}`;

  const mascotYesUrl = useBaseUrl("/img/reaction-mascot-yes.webp");
  const mascotNoUrl = useBaseUrl("/img/reaction-mascot-no.webp");

  const [counts, setCounts] = useState<Counts | null>(null);
  // null until the client-side effect runs — avoids SSR/hydration mismatch (#418).
  // If voted were read in useState(), SSR would produce null (no localStorage)
  // while the client would produce "helpful", causing a React tree mismatch.
  const [voted, setVoted] = useState<string | null>(null);
  const [submitError, setSubmitError] = useState(false);

  useEffect(() => {
    try {
      const stored = localStorage.getItem(storageKey);
      // eslint-disable-next-line react-hooks/set-state-in-effect -- intentional SSR/hydration-safe read, see comment on `voted` above
      if (stored) setVoted(stored);
    } catch {}
  }, [storageKey]);

  useEffect(() => {
    if (!slug) return;
    fetch(`${apiUrl}?slug=${encodeURIComponent(slug)}`)
      .then((r) => (r.ok ? r.json() : null))
      .then((data) => {
        if (data) setCounts(data);
      })
      .catch(() => {});
  }, [slug, apiUrl]);

  const handleVote = useCallback(
    async (vote: string) => {
      setSubmitError(false);
      try {
        const res = await fetch(apiUrl, {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ slug, vote }),
        });
        if (!res.ok) {
          setSubmitError(true);
          return;
        }
        const data = await res.json();
        setCounts(data);
        setVoted(vote);
        try {
          localStorage.setItem(storageKey, vote);
        } catch {}
      } catch {
        setSubmitError(true);
      }
    },
    [slug, apiUrl, storageKey],
  );

  if (!slug) return null;

  return (
    <div className={styles.container}>
      {!voted ? (
        <>
          <span className={styles.question}>
            <Translate id="blog.reaction.question">Was this article helpful?</Translate>
          </span>
          <div className={styles.buttons}>
            <button
              className={styles.btn}
              onClick={() => handleVote("helpful")}
              aria-label={translate({
                id: "blog.reaction.yes.ariaLabel",
                message: "Yes, this was helpful",
              })}
            >
              <img src={mascotYesUrl} alt="" className={styles.mascot} />
              <Translate id="blog.reaction.yes">Helpful</Translate>
            </button>
            <button
              className={`${styles.btn} ${styles.btnNeutral}`}
              onClick={() => handleVote("not_helpful")}
              aria-label={translate({
                id: "blog.reaction.no.ariaLabel",
                message: "No, this was not helpful",
              })}
            >
              <img src={mascotNoUrl} alt="" className={styles.mascot} />
              <Translate id="blog.reaction.no">Not really</Translate>
            </button>
          </div>
          {submitError && (
            <span className={styles.submitError}>
              <Translate id="reaction.saveError">
                Could not save your vote — please try again.
              </Translate>
            </span>
          )}
        </>
      ) : (
        <div className={styles.thanks}>
          <span className={styles.thanksMsg}>
            {voted === "helpful"
              ? translate({ id: "reaction.thanksHelpful", message: "Glad it helped! 🙌" })
              : translate({
                  id: "reaction.thanksNotHelpful",
                  message: "Thanks for the feedback!",
                })}
          </span>
          {counts && (
            <span className={styles.counts}>
              <span
                title={translate(
                  { id: "reaction.countHelpful", message: "{count} found this helpful" },
                  { count: counts.helpful },
                )}
              >
                👍 {counts.helpful}
              </span>
              <span
                title={translate(
                  {
                    id: "reaction.countNotHelpful",
                    message: "{count} did not find this helpful",
                  },
                  { count: counts.not_helpful },
                )}
              >
                👎 {counts.not_helpful}
              </span>
            </span>
          )}
        </div>
      )}
    </div>
  );
}
```

**src/components/Reaction/styles.module.css**

```css
/*
 * ⚠️ DUPLICATION — Reaction/styles.module.css and TriedIt/styles.module.css are
 * the SAME FILE, byte for byte, except that Reaction adds .submitError. Two
 * components, one widget: a question, a row of buttons, a thank-you state and
 * a count. They were tokenised identically here so they stay in step, but the
 * real fix is to have one of them import the other's stylesheet (CSS modules
 * support `composes: … from "../Reaction/styles.module.css"`), or to extract a
 * shared Feedback component. Flagged, not done: that is a refactor decision,
 * not a styling one.
 *
 * Fixed while tokenising: the hover filled the button with solid primary and
 * set `color: white` — a literal, and the only white text on terracotta in
 * this part of the site. It now uses --mk-on-line, which flips with the theme
 * (in dark mode the primary lightens, so white-on-it fails contrast).
 */

.container {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 0.75rem;
  padding: 0.9rem 1.25rem;
  margin: 1.5rem 0 0.5rem;
  border: 1px solid var(--mk-border);
  border-radius: var(--mk-radius-md);
  background: var(--mk-surface);
  box-shadow: var(--mk-shadow-1);
}

.question {
  font-weight: 600;
  color: var(--mk-ink);
  white-space: nowrap;
}

.buttons {
  display: flex;
  gap: 0.5rem;
  flex-wrap: wrap;
}

.btn {
  display: inline-flex;
  align-items: center;
  gap: 0.35rem;
  padding: 0.35rem 0.85rem;
  font-family: inherit;
  border: 1px solid var(--mk-border-strong);
  border-radius: var(--mk-radius-sm);
  background: transparent;
  color: var(--mk-ink);
  font-size: 0.875rem;
  cursor: pointer;
  transition:
    background-color 0.15s ease,
    border-color 0.15s ease,
    color 0.15s ease;
}

.mascot {
  width: 1.5rem;
  height: 1.5rem;
  object-fit: contain;
}

.btn:hover {
  background-color: var(--mk-primary);
  border-color: var(--mk-primary);
  color: var(--mk-on-line);
}

.btn:focus-visible {
  outline: 2px solid var(--mk-primary);
  outline-offset: 2px;
}

.btnNeutral:hover {
  background-color: var(--mk-n-300);
  border-color: var(--mk-n-300);
  color: var(--mk-n-900);
}

.thanks {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 1rem;
}

.thanksMsg {
  font-weight: 600;
  color: var(--mk-ink);
}

.counts {
  display: flex;
  gap: 0.75rem;
  font-size: 0.875rem;
  color: var(--mk-ink-soft);
  font-variant-numeric: tabular-nums;
}

.submitError {
  font-size: 0.8rem;
  color: var(--mk-danger-line);
  width: 100%;
}
```

**src/pages/reactions-dashboard.js**

```javascript
import { useState, useEffect, useCallback } from "react";
import PropTypes from "prop-types";
import Layout from "@theme/Layout";
import Head from "@docusaurus/Head";
import useDocusaurusContext from "@docusaurus/useDocusaurusContext";
import styles from "./reactions-dashboard.module.css";

// ── Data helpers ─────────────────────────────────────────────────────────────

function computeTotals(data) {
  let totalHelpful = 0;
  let totalNot = 0;

  const rows = Object.entries(data)
    .map(([slug, counts]) => {
      const helpful = counts.helpful ?? 0;
      const notHelpful = counts.not_helpful ?? 0;
      const total = helpful + notHelpful;
      const ratio = total > 0 ? Math.round((helpful / total) * 100) : 0;
      totalHelpful += helpful;
      totalNot += notHelpful;
      return { slug, helpful, notHelpful, total, ratio };
    })
    .sort((a, b) => b.helpful - a.helpful || b.total - a.total);

  const grandTotal = totalHelpful + totalNot;
  const approval = grandTotal > 0 ? Math.round((totalHelpful / grandTotal) * 100) : 0;

  return { rows, totalHelpful, totalNot, grandTotal, approval };
}

// ── Sub-components ───────────────────────────────────────────────────────────

function SummaryCards({ totalHelpful, totalNot, grandTotal, approval }) {
  return (
    <div className={styles.summary}>
      <div className={styles.card}>
        <div className={styles.cardValue}>{grandTotal}</div>
        <div className={styles.cardLabel}>Total votes</div>
      </div>
      <div className={styles.card}>
        <div className={styles.cardValue}>👍 {totalHelpful}</div>
        <div className={styles.cardLabel}>Helpful</div>
      </div>
      <div className={styles.card}>
        <div className={styles.cardValue}>👎 {totalNot}</div>
        <div className={styles.cardLabel}>Not helpful</div>
      </div>
      <div className={styles.card}>
        <div className={styles.cardValue}>{approval}%</div>
        <div className={styles.cardLabel}>Approval rate</div>
      </div>
    </div>
  );
}

SummaryCards.propTypes = {
  totalHelpful: PropTypes.number.isRequired,
  totalNot: PropTypes.number.isRequired,
  grandTotal: PropTypes.number.isRequired,
  approval: PropTypes.number.isRequired,
};

function ApprovalBar({ ratio }) {
  return (
    <div className={styles.barWrap}>
      <div className={styles.bar}>
        <div className={styles.barFill} style={{ width: `${ratio}%` }} />
      </div>
      <span className={styles.barLabel}>{ratio}%</span>
    </div>
  );
}

ApprovalBar.propTypes = {
  ratio: PropTypes.number.isRequired,
};

function ReactionsTable({ rows, siteUrl }) {
  if (rows.length === 0) {
    return <p className={styles.empty}>No reactions recorded yet.</p>;
  }

  return (
    <table className={styles.table}>
      <thead>
        <tr>
          <th>Article</th>
          <th className={styles.right}>👍</th>
          <th className={styles.right}>👎</th>
          <th className={styles.right}>Total</th>
          <th>Approval</th>
        </tr>
      </thead>
      <tbody>
        {rows.map(({ slug, helpful, notHelpful, total, ratio }) => (
          <tr key={slug}>
            <td>
              <a
                href={`${siteUrl}/${slug}`}
                target="_blank"
                rel="noopener noreferrer"
                className={styles.articleLink}
              >
                {slug}
              </a>
            </td>
            <td className={styles.right}>{helpful}</td>
            <td className={styles.right}>{notHelpful}</td>
            <td className={styles.right}>{total}</td>
            <td>
              <ApprovalBar ratio={ratio} />
            </td>
          </tr>
        ))}
      </tbody>
    </table>
  );
}

ReactionsTable.propTypes = {
  rows: PropTypes.arrayOf(
    PropTypes.shape({
      slug: PropTypes.string.isRequired,
      helpful: PropTypes.number.isRequired,
      notHelpful: PropTypes.number.isRequired,
      total: PropTypes.number.isRequired,
      ratio: PropTypes.number.isRequired,
    }),
  ).isRequired,
  siteUrl: PropTypes.string.isRequired,
};

function AuthForm({ onSubmit }) {
  const [token, setToken] = useState("");

  return (
    <div className={styles.authWrap}>
      <p>Enter your admin token to view the dashboard.</p>
      <form
        className={styles.authForm}
        onSubmit={(e) => {
          e.preventDefault();
          onSubmit(token.trim());
        }}
      >
        <input
          className={styles.authInput}
          type="password"
          placeholder="Admin token"
          value={token}
          onChange={(e) => setToken(e.target.value)}
          autoFocus
        />
        <button className={styles.authBtn} type="submit">
          View
        </button>
      </form>
    </div>
  );
}

AuthForm.propTypes = {
  onSubmit: PropTypes.func.isRequired,
};

const STORAGE_KEY = "reactions_admin_token";

// ── Page ─────────────────────────────────────────────────────────────────────

export default function ReactionsDashboard() {
  const { siteConfig } = useDocusaurusContext();
  const apiUrl = `${siteConfig.url}/api/reactions.php`;

  const [token, setToken] = useState("");
  const [data, setData] = useState(null);
  const [error, setError] = useState(null);
  const [loading, setLoading] = useState(false);

  // Priority: URL hash → localStorage → empty (show form).
  // Must run in useEffect — localStorage is unavailable during SSR,
  // and React does not re-run useState initializers on client hydration.
  useEffect(() => {
    const initial =
      window.location.hash.slice(1) || localStorage.getItem(STORAGE_KEY) || "";
    // eslint-disable-next-line react-hooks/set-state-in-effect -- intentional SSR/hydration-safe read, see comment above
    if (initial) setToken(initial);
  }, []);

  const fetchData = useCallback(
    async (t) => {
      if (!t) return;
      setLoading(true);
      setError(null);
      try {
        const res = await fetch(`${apiUrl}?admin=${encodeURIComponent(t)}`);
        if (res.status === 403) {
          localStorage.removeItem(STORAGE_KEY);
          setError("Invalid token.");
          setData(null);
          return;
        }
        if (!res.ok) throw new Error(`HTTP ${res.status}`);
        localStorage.setItem(STORAGE_KEY, t);
        setData(await res.json());
      } catch (e) {
        setError(`Failed to load data: ${e.message}`);
        setData(null);
      } finally {
        setLoading(false);
      }
    },
    [apiUrl],
  );

  // Reactive sync: refetch whenever the token changes (login, restore from storage, hash link).
  useEffect(() => {
    // eslint-disable-next-line react-hooks/set-state-in-effect -- fetchData sets state, but this is a legitimate reaction to `token` changing, not derivable at render time
    if (token) fetchData(token);
  }, [token, fetchData]);

  const handleTokenSubmit = (t) => {
    setToken(t);
    fetchData(t);
  };

  const handleForget = () => {
    localStorage.removeItem(STORAGE_KEY);
    setToken("");
    setData(null);
    setError(null);
  };

  const stats = data ? computeTotals(data) : null;

  return (
    <Layout title="Reactions Dashboard" noFooter>
      <Head>
        <meta name="robots" content="noindex, nofollow" />
      </Head>

      <div className={styles.page}>
        <div className={styles.header}>
          <h1>Reactions Dashboard</h1>
          <p className={styles.subtitle}>
            Per-article reader feedback — sorted by helpful count
          </p>
        </div>

        {!token && <AuthForm onSubmit={handleTokenSubmit} />}

        {token && loading && <p>Loading…</p>}

        {token && error && <p className={styles.error}>{error}</p>}

        {stats && (
          <>
            <SummaryCards {...stats} />
            <ReactionsTable rows={stats.rows} siteUrl={siteConfig.url} />
            <button className={styles.forgetBtn} onClick={handleForget}>
              Forget token
            </button>
          </>
        )}
      </div>
    </Layout>
  );
}
```

***

## Security Considerations

A few things to keep in mind before deploying:

**Change the `ADMIN_TOKEN`.**  The example in the repository uses a placeholder. Generate your own with `openssl rand -base64 32` and update the constant before deploying. Anyone with this token can read every vote ever recorded.

**`reactions-data.json` and `notifications.json` should not be publicly accessible.**  If your web server serves the `api/` folder directly, make sure these JSON files are not downloadable by just navigating to them. Add an `.htaccess` rule to block direct access to `*.json` files inside that directory:

```apacheconf title="api/.htaccess"
<FilesMatch "\.json$">
    Require all denied
</FilesMatch>
```

**The PHP script does not authenticate voters.**  Anyone can POST multiple votes for the same article from different clients. `localStorage` only prevents double voting from the same browser, not from scripts or different devices. For a personal blog, this is an acceptable trade-off — you get signal, not precision polling data.

**File permissions.**  Make sure `api/reactions-data.json` and `api/notifications.json` are writable by the web server user. The script creates them on first use, so the `api/` directory itself must be writable. On Linux: `chmod 775 api/` and ensure the web server user owns or is in the group of that folder.

***

## Testing It

Once the files are in place:

1. **Start the Docusaurus dev server**: `yarn start`
2. Open any blog post. You should see the "Was this article helpful?" widget at the bottom.
3. Click one of the buttons. The widget should switch to the thank-you state.
4. Refresh the page. The widget should still show the thank-you state (loaded from `localStorage`).
5. Open a different browser (or an incognito window) and reload the same article. The vote counts from step 3 should be visible after voting.
6. Visit `/reactions-dashboard` and enter your admin token. The article you just voted on should appear in the table.

> **The dashboard URL:**
>
> You can bookmark `/reactions-dashboard#your-token` to open the dashboard directly. The token in the hash fragment is never sent to the server in the HTTP request, so it does not appear in server access logs.

***

## Conclusion

The entire system is about 250 lines of code across five files, has no external dependencies beyond what Docusaurus already ships, and requires nothing on the infrastructure side except a server capable of running PHP.

What I like most about this approach is that every byte of data lives in your own files, under your own control. Votes are stored in a plain JSON file you can open with any text editor, back up with any tool, and migrate to any other system whenever you want. No SaaS subscription to cancel, no API key to renew, no privacy policy to update because someone else's SDK added a tracker.

If you build on this and add features — per-section reactions, reader questions, [outdated flags](/blog/docusaurus-old-notice) — the same pattern scales naturally: one PHP file per feature, one React component, one JSON store.
