Short-link click tracking from a Cloudflare Worker with Get Butters

Roger StringerRoger Stringer
November 26, 2026
6 min read
Short-link click tracking from a Cloudflare Worker with Get Butters

A short link never shows anyone a page. Someone taps rser.me/r/talk, the Worker answers with a 302, and the browser is gone before a layout, a script tag or an analytics snippet gets a chance to load.

That's why page analytics can't count short links. Your tracking script never runs on a redirect.

I covered the basic wiring in the bonus section of the rser.me build post. This post goes further: why each piece of the server-side tracker is shaped the way it is, what it deliberately leaves out, and how I read the results afterward. The events go to Get Butters, the event feed I built (here's the intro), and the full code is in the rser.me repo.

Track at the redirect, not on the page

A short link has exactly one place where code runs: the route that looks up the destination and returns the redirect. So that's where the tracking call goes, one line before the response:

---
// src/pages/r/[code].astro
import { decodeSlug, getEmDashEntry, sanitizeHref } from "emdash";
import { trackRedirect } from "../../utils/butters";

const code = decodeSlug(Astro.params.code);
if (!code) return Astro.rewrite("/404");

const { entry: link, cacheHint } = await getEmDashEntry("r", code);
const url = link?.data.url ? sanitizeHref(link.data.url) : null;
if (Astro.cache?.enabled) Astro.cache.set(cacheHint);
if (!url || url === "#") return Astro.rewrite("/404");

trackRedirect(Astro.request, `/r/${code}`, url, "r");
return Astro.redirect(url, 302);
---

Two details matter here.

The call sits after the 404 checks, so a mistyped code never becomes an event. And it's a 302, which keeps the count honest. A 301 gets cached by the browser, so the second tap on the same link never reaches the Worker and never gets counted. (The build post has the longer argument for 302s. Tracking is a second reason.)

The site has two kinds of short links: /r/<code> entries from their own collection, and link cards on the page that double as rser.me/<slug>. Both routes call trackRedirect, with a source of "r" or "block", so I can tell them apart in the feed later.

Never make the visitor wait

The rule for tracking a redirect: the visitor's redirect can't wait on my analytics. If Butters is slow, or down, or the request fails, the 302 still goes out at full speed.

On Workers, waitUntil does exactly that. It lets the response leave while a promise keeps running in the background:

// src/utils/butters.ts (trimmed)
import { env, waitUntil } from "cloudflare:workers";

const config = env as unknown as { BUTTERS_API_KEY?: string; BUTTERS_PROJECT_ID?: string };

export function track(event: ButtersEvent): void {
	const apiKey = config.BUTTERS_API_KEY;
	const project = config.BUTTERS_PROJECT_ID;
	if (!apiKey || !project) return;

	const send = fetch("https://app.getbutters.com/api/events", {
		method: "POST",
		headers: { "Content-Type": "application/json", Authorization: `Bearer ${apiKey}` },
		body: JSON.stringify({ project, ...event }),
	})
		.then(async (res) => {
			if (!res.ok) console.warn(`[butters] ${res.status} ${(await res.text()).slice(0, 200)}`);
		})
		.catch((err) => console.warn("[butters] send failed:", err));

	waitUntil(send);
}

A few choices in there are on purpose:

  • waitUntil comes from cloudflare:workers. An Astro page doesn't get the Worker's ctx handed to it, and threading it through every route would be ugly. The module import works anywhere in the request.
  • track returns void and never throws. Every failure ends in a console.warn. A tracking bug can show up in the Worker logs, but it can't take down a redirect.
  • No keys, no tracking. Without BUTTERS_API_KEY and BUTTERS_PROJECT_ID it returns early. A fork of the repo works fine with tracking off, and nothing errors.

The original repo version also reads an optional BUTTERS_URL, so you can point it at a self-hosted instance or a staging app.

Filter out the clicks no human made

This is the part that matters most for short links in particular.

Paste a link into Slack, iMessage, Discord or a social post, and a preview crawler fetches it to build the card. That happens before any person sees the link. Without a filter, every link you share starts life with at least one fake click, and some services fetch it more than once.

// Link-preview crawlers and bots (Slack, iMessage, social cards, uptime checks).
const BOT_UA =
	/bot\b|bot\/|crawl|spider|slurp|preview|facebookexternalhit|embedly|whatsapp|telegram|discord|skype|vkshare|pinterest|headless|lighthouse|uptime|monitor|curl\/|wget\/|python-requests|go-http-client/i;

export function isBot(request: Request): boolean {
	const ua = request.headers.get("user-agent") ?? "";
	return ua === "" || BOT_UA.test(ua);
}

An empty user agent counts as a bot. Real browsers always send one, and scripts often don't.

The list also catches tooling: curl/, wget/ and uptime monitors. Testing a link from the terminal shouldn't count as a visit.

It's a blunt regex, and it'll miss a crawler that pretends to be Chrome. For a personal link page that's fine. I'd rather undercount than celebrate a spike that turns out to be Slackbot.

Local development gets the same treatment. isLocal() checks for localhost, 127.0.0.1 and .local hosts, so clicking around in astro dev never sends a thing.

Record context, not people

Each redirect event carries a little context about the visit. Here's the whole function:

/** Visitor context without personal data: country, referring site, device type. */
export function requestContext(request: Request): Record<string, string> {
	const ctx: Record<string, string> = {};
	const country = request.headers.get("cf-ipcountry");
	if (country && country !== "XX") ctx.country = country;
	const referrer = request.headers.get("referer");
	if (referrer) {
		try {
			ctx.referrer = new URL(referrer).hostname;
		} catch {
			/* ignore malformed referrers */
		}
	}
	const ua = request.headers.get("user-agent") ?? "";
	ctx.device = /mobile|iphone|android/i.test(ua) ? "mobile" : /ipad|tablet/i.test(ua) ? "tablet" : "desktop";
	return ctx;
}

What's missing is as deliberate as what's there.

There's no IP address. Cloudflare already resolves the country and puts it in cf-ipcountry, so I take that and drop the rest (XX means unknown, so it's skipped). The referrer is cut down to its hostname, because a full referrer URL can carry search terms or tokens in its query string. And the user agent becomes one of three words.

That's enough to answer the questions I have: where a link got shared, and whether people opened it on a phone. And I don't have to think about storing anything sensitive.

The event itself puts the short path in the title and the destination in the event's link:

export function trackRedirect(request: Request, path: string, destination: string, source: "r" | "block") {
	if (isBot(request) || isLocal(new URL(request.url))) return;
	track({
		category: "short-links",
		title: path,
		icon: "🔗",
		url: destination,
		metadata: { path, destination, source, ...requestContext(request) },
	});
}

In the Butters feed, that reads as a line per click, 🔗 /r/talk, and clicking the title opens the destination.

Two keys, two jobs

The page half of the site tracks link-card and social clicks in the browser with the @getbutters/js SDK. That means two different keys, and the split is the important part:

  • BUTTERS_API_KEY (ev_...) is the secret key. It can write events to any project, so it only exists as a Worker secret and never reaches the browser.
  • PUBLIC_BUTTERS_KEY (pk_...) is publishable. It ends up in the page HTML, so it's restricted to the site's domain in Butters.
bunx wrangler secret put BUTTERS_API_KEY
bunx wrangler secret put BUTTERS_PROJECT_ID
bunx wrangler secret put PUBLIC_BUTTERS_KEY

The browser component also renders nothing on localhost or without a key, using the same isLocal() check as the server. One rule for both halves keeps them from drifting apart.

Reading the numbers

Every event lands in a category: short-links from the server, and clicks, socials, dialogs and forms from the browser. Butters charts daily counts per category, so "how much do short links get used compared to the cards on the page" is one chart away.

The metadata is where the specific questions get answered. Which code gets the most taps, whether /r/ links or link-card links get used more (the source field), and which hostnames send people in.

Butters also has an MCP server, so I can ask Claude for a project's daily counts in the short-links category without opening the dashboard. And for a number I want pinned to the top of the project, there's the KPI insight card. The CLI upserts one by title, so the same command run again updates the same card:

butters insight --project <project-id> --title "Short-link taps (7d)" --value "<count>" --icon "🔗"

[ROGER: one or two lines on what the feed has actually shown you since click tracking went live, e.g. which link gets used most or where shares come from. Or cut this placeholder.]

What this cost

Roughly 100 lines of TypeScript for the server half, one import per redirect route, and three secrets. The server half sets no cookie and stores no personal data. And the redirect is exactly as fast as it was before tracking existed.

If you're running short links on Workers and only counting page views, you're blind to the links you share most. The repo is at github.com/freekrai/rser.me if you want to lift src/utils/butters.ts as-is. And if you want the broader picture of how I use the feed across my products, I wrote up tracking signups, logins and errors with Get Butters.

Tagged In:

Do you like my content?

Sponsor Me On Github

Keep reading

Weekly Digest

One email a week with everything new here: posts, field guides and bookmarks. Nothing else, and you can unsubscribe any time.