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

@ -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;