Links/redirects: /go/ short links with click counts, Plausible and UTM tags (migration 068)

Data > Links/redirects (editors and up) makes short links on our
domain. GET /go/<id> counts the click, reports it to Plausible as a
pageview of /go/<id> (the visitor's browser and address, no key
needed), and redirects (302, no-store) with the link's UTM tags added
to the destination. Unknown ids fall through to the not-found page.
The editor can show a fixed lead-in in the URL ID box (idPrefix).
Vite proxies /go in dev. docs/redirects.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Zaldimmar 2026-10-05 00:37:26 -05:00
parent 3fafd7f92c
commit 6289e7203f
13 changed files with 284 additions and 4 deletions

View file

@ -56,6 +56,7 @@ import { siteSettings } from "./admin-schema/siteSettings.js";
import { newsletters } from "./admin-schema/newsletters.js";
import { personTagTypes } from "./admin-schema/personTags.js";
import { contactTypes } from "./admin-schema/contactTypes.js";
import { redirects } from "./admin-schema/redirects.js";
import {
communityPage,
retreatsPage,
@ -70,6 +71,7 @@ export const ENTITIES = {
people,
person_tag_types: personTagTypes,
contact_types: contactTypes,
redirects,
teams,
awards,
timeline,

View file

@ -0,0 +1,30 @@
import { text, url } from "./columns.js";
/* ── Links/redirects (068_redirects.sql) ─────────────────────────
Short links on our domain, /go/<id>, answered by
routes/redirects.js. clicks and last_clicked_at are the route's,
so they're listed but never written from here: a save can't reset
a count. */
export const redirects = {
key: "redirects",
table: "redirects",
idColumn: "id",
idKind: "slug",
list: {
columns: ["id", "target_url", "clicks", "last_clicked_at"],
filters: [],
search: ["id", "target_url", "note", "utm_campaign"],
order: "id",
},
columns: [
url("target_url", { required: true }),
text("note"),
text("utm_source"),
text("utm_medium"),
text("utm_campaign"),
],
};

View file

@ -31,7 +31,7 @@ import { pathToFileURL } from "node:url";
import { siteFor } from "./pageMeta.js";
const PLAUSIBLE_URL = (process.env.PLAUSIBLE_URL || "http://127.0.0.1:8000").replace(/\/$/, "");
export const PLAUSIBLE_URL = (process.env.PLAUSIBLE_URL || "http://127.0.0.1:8000").replace(/\/$/, "");
const PLAUSIBLE_API_KEY = process.env.PLAUSIBLE_API_KEY || null;
const DISCORD_WEBHOOK_URL = process.env.DISCORD_WEBHOOK_URL || null;
const REPORT_TZ = process.env.REPORT_TZ || "America/Chicago";

View file

@ -40,6 +40,7 @@ import clips from "./routes/clips.js";
import imports from "./routes/import.js";
import files from "./routes/files.js";
import countdown from "./routes/countdown.js";
import redirects from "./routes/redirects.js";
import { CLIPS_DIR, startClipWorker } from "./clips.js";
import { UPLOADS_DIR, writeMissingThumbs } from "./media.js";
import { logSafe, startSessionSweeper } from "./auth.js";
@ -235,6 +236,10 @@ app.use(
}),
);
// Short links, /go/<id> (routes/redirects.js); an unknown one falls
// through to the pages below.
app.route("/", redirects);
// Last: every other GET that isn't /api is a page of the site, sent
// with its metadata filled in (routes/pages.js).
app.route("/", pages);

View file

@ -0,0 +1,32 @@
-- ═══════════════════════════════════════════════════════════════
-- 068 REDIRECTS
--
-- Short links on our own domain (Data → Links/redirects), eg.
-- /go/retreat-signup, for the newsletter and anywhere else a link
-- should be counted. routes/redirects.js answers /go/<id>: it counts
-- the click here, tells Plausible about it, and sends the visitor on
-- with the link's UTM tags added.
--
-- target_url where it goes: a web address, or a path on this
-- site starting with /
-- utm_* added to the destination's query, when set
-- clicks, kept by the redirect route, not the editor
-- last_clicked_at
-- ═══════════════════════════════════════════════════════════════
CREATE TABLE redirects (
id TEXT PRIMARY KEY
CONSTRAINT "A redirect's URL ID can use only lowercase letters, numbers and hyphens, eg. retreat-signup."
CHECK (id <> '' AND id NOT GLOB '*[^a-z0-9-]*'),
target_url TEXT NOT NULL
CONSTRAINT "A redirect goes to a web address (https://...) or a path on this site starting with /."
CHECK (target_url GLOB 'https://?*' OR target_url GLOB 'http://?*'
OR (target_url GLOB '/*' AND target_url NOT GLOB '//*')),
note TEXT, -- what it's for, admin only
utm_source TEXT, -- 'newsletter'
utm_medium TEXT, -- 'email'
utm_campaign TEXT, -- 'october-2026'
clicks INTEGER NOT NULL DEFAULT 0,
last_clicked_at TEXT,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
) STRICT;

View file

@ -0,0 +1,89 @@
/* ═══════════════════════════════════════════════════════════════
REDIRECTS: GET /go/:id
A short link from Data → Links/redirects (068). Each visit:
1. adds one to the link's clicks (shown in the admin list)
2. tells Plausible, as a pageview of /go/<id> with the visitor's
browser and address, since a redirect never loads the page
script; it shows under Top Pages like any page
3. sends the visitor on (302) to the destination, with the link's
UTM tags added to its query, so a click that lands on a
tracked site is credited to the newsletter
Never cached, so every click reaches here. An unknown id falls
through to the page route, which shows the site's not-found page.
Plausible is at PLAUSIBLE_URL (analyticsReport.js); if it can't
be reached the redirect still happens, and that's logged once.
Mounted before routes/pages.js. In production nginx sends /go/
here through its catch-all page block; in development Vite
proxies /go (vite.config.ts).
═══════════════════════════════════════════════════════════════ */
import { Hono } from "hono";
import { PLAUSIBLE_URL } from "../analyticsReport.js";
import { clientIp } from "../auth.js";
import { siteFor } from "../pageMeta.js";
import { NO_STORE } from "../shape.js";
const UTM = ["utm_source", "utm_medium", "utm_campaign"];
/* The destination with the link's UTM tags, any it already carries
kept. A path on this site stays a path. */
export function destination(row, origin) {
const local = row.target_url.startsWith("/");
const url = new URL(row.target_url, origin);
for (const key of UTM) {
if (row[key] && !url.searchParams.has(key)) url.searchParams.set(key, row[key]);
}
return local ? `${url.pathname}${url.search}${url.hash}` : url.href;
}
let plausibleWarned = false;
function tellPlausible(c, site, id) {
let domain;
try {
domain = new URL(site.url).hostname;
} catch {
return; // no site url, nothing to count under
}
const ip = clientIp(c);
fetch(`${PLAUSIBLE_URL}/api/event`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"User-Agent": c.req.header("user-agent") ?? "",
...(ip ? { "X-Forwarded-For": ip } : {}),
},
body: JSON.stringify({
name: "pageview",
domain,
url: `${site.url.replace(/\/$/, "")}/go/${id}`,
referrer: c.req.header("referer") ?? null,
}),
signal: AbortSignal.timeout(5_000),
}).catch((err) => {
if (plausibleWarned) return;
plausibleWarned = true;
console.warn(`redirects: couldn't reach Plausible at ${PLAUSIBLE_URL} (${err.message}); clicks are still counted`);
});
}
const redirects = new Hono();
redirects.get("/go/:id", (c, next) => {
const db = c.get("db");
const row = db.prepare(`SELECT * FROM redirects WHERE id = ?`).get(c.req.param("id").toLowerCase());
if (!row) return next();
db.prepare(`UPDATE redirects SET clicks = clicks + 1, last_clicked_at = datetime('now') WHERE id = ?`).run(row.id);
const site = siteFor(db);
tellPlausible(c, site, row.id);
for (const [name, value] of Object.entries(NO_STORE)) c.header(name, value);
return c.redirect(destination(row, site.url || "http://localhost"), 302);
});
export default redirects;