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

@ -32,7 +32,7 @@ In dev, Vite proxies `/api` to the target set in `vite.config.ts`, so the API mu
- Debugging: check `journalctl -u ngu-api -n 40 --no-pager` first. Make sure rsync ran from the repo (not the deployed copy) before restarting the service.
- Never run commands against the production server or database unless explicitly asked.
- Uploaded media: `UPLOADS_DIR=/var/lib/ngu/uploads`, served by nginx at `/uploads/`. Setup and the nginx block are in `docs/media-uploads.md`.
- Analytics: self-hosted Plausible, proxied by nginx at `/pa/`. The API adds its script to every page (`analyticsTag` in `server/src/pageMeta.js`), counting under the hostname of `site.json`'s `url`, so each deployment reports as itself. Nothing in `index.html` or the app. Daily and weekly reports go to Discord when Panel → Site settings → Reports turns them on and `PLAUSIBLE_API_KEY` and `DISCORD_WEBHOOK_URL` are set (`server/src/analyticsReport.js`): `docs/analytics-reports.md`.
- Analytics: self-hosted Plausible, proxied by nginx at `/pa/`. The API adds its script to every page (`analyticsTag` in `server/src/pageMeta.js`), counting under the hostname of `site.json`'s `url`, so each deployment reports as itself. Nothing in `index.html` or the app. Daily and weekly reports go to Discord when Panel → Site settings → Reports turns them on and `PLAUSIBLE_API_KEY` and `DISCORD_WEBHOOK_URL` are set (`server/src/analyticsReport.js`): `docs/analytics-reports.md`. Short links `/go/<id>` (Data → Links/redirects, `server/src/routes/redirects.js`) count clicks, report each to Plausible as a pageview and add the link's UTM tags: `docs/redirects.md`.
- Page HTML goes through the API, which fills in each page's title, description, preview image and structured data (`server/src/pageMeta.js`), and serves `/sitemap.xml`. It reads `SITE_CONFIG` (site.json) and `SITE_INDEX` (the built index.html), with Panel → Site settings (the `site_settings` table) laid over site.json, and serves `/robots.txt` from the same merge. nginx setup: `docs/seo.md`.
- Video clips (Tools, admins and up): yt-dlp downloads our YouTube/Facebook videos into `CLIPS_DIR`, ffmpeg cuts them; one job at a time, files swept after a day (`server/src/clips.js`). Needs yt-dlp and ffmpeg on the VPS: `docs/video-clips.md`.
- Newsletter countdown pictures: `/api/countdown/:id.png` (`server/src/routes/countdown.js`), drawn with sharp when an email is opened; it uses the VPS's fonts, so install Poppins there (eg. into `/usr/local/share/fonts`, then `fc-cache`) or it falls back to a plain sans. The social bar's icons are static files in `public/email/`.

53
docs/redirects.md Normal file
View file

@ -0,0 +1,53 @@
# Links/redirects
Short links on our own domain, made in Admin → Data → Links/redirects
(editors and up), eg. `nextgenerationofunity.org/go/retreat-signup`. Use
them in the newsletter, or anywhere else, so each click is counted.
Each link has:
- **URL ID**: the part after `/go/`. Lowercase letters, numbers and
hyphens, and it can't be changed once made, since it's already been
sent out.
- **Goes to**: a web address (`https://...`) or a page on this site
(`/retreats`). This can be changed at any time, and every copy of the
link already sent follows it.
- **Note**: what it's for. Only we see it.
- **UTM tags** (source, medium, campaign): added to the destination's
address, eg. `?utm_source=newsletter&utm_medium=email&utm_campaign=october-2026`.
A tag the destination already has is left as it is.
## What a click does
`GET /go/<URL ID>` (`server/src/routes/redirects.js`, migration 068):
1. Adds one to the link's **Clicks** and sets **Last click** (both on
the list page). A save in the editor never changes them.
2. Tells Plausible, as a pageview of `/go/<URL ID>` with the visitor's
browser and address, so it appears in Top Pages (and in the Discord
reports) like any page. A redirect never loads the page script, so
the server reports it. It uses `PLAUSIBLE_URL`, the same as the
reports (`docs/analytics-reports.md`), and needs no API key. If
Plausible can't be reached, the redirect still works and the
problem is logged once.
3. Sends the visitor on with a 302. It's never cached, so every click
reaches the server.
An unknown URL ID shows the site's not-found page.
## Reading the numbers
- **Clicks** counts every request, including link checkers. Some email
security scanners open every link in a message before the reader
does, so a newsletter link can show a few clicks straight away.
Plausible leaves out known bots, so its count is usually lower and
closer to real readers.
- In Plausible, filter by page `/go/` to see every short link, or by a
UTM source or campaign to see what those visitors did once they
landed on our site.
## Setup
Nothing beyond the migration: nginx already sends `/go/...` to the API
through its catch-all page block (`nginx-dev`, `ngu-prod`). In
development, Vite proxies `/go` to the API (`vite.config.ts`).

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;

View file

@ -29,6 +29,7 @@ import { blogPosts } from "./adminSchema/blog.ts";
import { siteSettings } from "./adminSchema/siteSettings.ts";
import { personTagTypes } from "./adminSchema/personTags.ts";
import { contactTypes } from "./adminSchema/contactTypes.ts";
import { redirects } from "./adminSchema/redirects.ts";
import {
communityPage,
retreatsPage,
@ -43,6 +44,7 @@ export const ADMIN_ENTITIES: Record<string, any> = {
people,
person_tag_types: personTagTypes,
contact_types: contactTypes,
redirects,
teams,
awards,
timeline,

View file

@ -0,0 +1,53 @@
/* ── Links/redirects (068_redirects.sql) ─────────────────────────
Data → Links/redirects: short links on our own domain, /go/<URL ID>,
for the newsletter and anywhere a link should be counted. Each
click is counted here, sent to Plausible as a pageview of
/go/<URL ID>, and passed on with the link's UTM tags. Server side:
server/src/admin-schema/redirects.js and routes/redirects.js. */
import { SITE_ORIGIN } from "../site.ts";
const GO = `${SITE_ORIGIN.replace(/^https?:\/\//, "").replace(/\/$/, "")}/go/`;
export const redirects = {
key: "redirects",
label: "Links/redirects",
singular: "redirect",
idLabel: "URL ID",
idPrefix: GO,
list: {
columns: [
{ key: "id", label: "Link", primary: true },
{ key: "target_url", label: "Goes to" },
{ key: "clicks", label: "Clicks" },
{ key: "last_clicked_at", label: "Last click" },
],
filters: [],
},
groups: [
{
legend: "Redirect",
fields: [
{
path: "target_url",
label: "Goes to",
required: true,
full: true,
help: "A web address, eg. https://ngu.churchcenter.com/registrations/events/123, or a page on this site, eg. /retreats",
},
{ path: "note", label: "Note", full: true, help: "What it's for, for us only. eg. October newsletter, retreat button" },
],
},
{
legend: "Tracking (UTM tags)",
note: "Added to the destination, so a click that lands on our site (or another one with analytics) is credited to where the link was shared. Clicks are counted either way.",
fields: [
{ path: "utm_source", label: "Source", help: "eg. newsletter. Default: none" },
{ path: "utm_medium", label: "Medium", help: "eg. email. Default: none" },
{ path: "utm_campaign", label: "Campaign", help: "eg. october-2026. Default: none" },
],
},
],
};

View file

@ -431,8 +431,10 @@ export default function EntityEdit() {
field={{
path: "id",
label: manifest.idLabel,
prefix: isNew && qualifierPaths.length ? prefixOf(form) || prefixHint : undefined,
prefixPending: isNew && !prefixOf(form),
// A fixed lead-in shown in the box (redirects' domain/go/), or
// the qualifiers' prefix as it fills in.
prefix: isNew ? (qualifierPaths.length ? prefixOf(form) || prefixHint : manifest.idPrefix) : undefined,
prefixPending: isNew && qualifierPaths.length > 0 && !prefixOf(form),
placeholder: isNew && qualifierPaths.length ? "board" : undefined,
readOnly: !isNew,
help: !isNew

View file

@ -85,6 +85,11 @@ export const DATA_NAV = {
label: "People tags",
blurb: "Directories people can be tagged into, eg. Musicians. Who carries a tag is edited on the person.",
},
{
to: "/admin/redirects",
label: "Links/redirects",
blurb: "Short /go/ links for the newsletter, with click counts, Plausible and UTM tracking.",
},
{
to: "/admin/blog_posts",
label: "Blog posts",

View file

@ -22,6 +22,13 @@ export default defineConfig({
changeOrigin: false,
xfwd: true,
},
// Short links (server/src/routes/redirects.js): in production
// nginx's page block sends them to the API.
"/go": {
target: "http://127.0.0.1:3001",
changeOrigin: false,
xfwd: true,
},
// Uploaded images. nginx serves these in production; in dev
// the API does, so they go to the same place as /api.
"/uploads": {