Repository navigation
feat(tracker): post each visit to discord through a cloudflare worker - #3
Merged
Merged
Conversation
…d edit it as it goes on
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Adds visit tracking to ml3labs.com. Each visit shows up as a Discord post: which numbered browser it is, roughly where it came from, on what device, and what it did on the site.
The site is a static export on GitHub Pages, so nothing can run on a server at request time. The tracking lives in a small Cloudflare Worker with a D1 database under
tracker/. The site sends it a beacon when a visit starts. The Worker numbers the browser ("Visitor #N", "2nd visit"), adds location and network from Cloudflare's request data, and posts a Discord embed through a webhook. When the tab hides, the site sends the pages seen, the time on each and the links clicked, and the Worker edits that same post. The webhook URL is a Worker secret. The page only knows the Worker's address, and tracks nothing unlessNEXT_PUBLIC_TRACKER_URLis set.How it works
Key invariant: one Discord post per visit, edited in place. A reload in the same tab carries on the visit it belongs to: the site doesn't send
/visitagain, and the Worker ignores a visit id it has already claimed. Events that arrive while the post is still on its way are shown as soon as it lands.Both beacons go by
sendBeaconastext/plainJSON, so they need no CORS and still go out as the page closes. The page never reads a reply.Data model
D1 (
tracker/schema.sql, safe to run again: everything isIF NOT EXISTS)counters: the running visitor numbervisitors: one row per browser, keyed by the random id it keeps in localStorage. Holds its visitor number, its visit count and when it was first seensessions: one row per visit (a tab's session). Holds its start, last update and duration, the Discord message id, the pages and clicks as JSON, plus country, region, city, network, device, browser, OS, language, referrer and entry page. Indexed by start timeNo IP addresses are stored. The IP appears only in the Discord post, and only for desktop visits. Because Discord replaces a post's embeds whole, the Worker reads the post back from Discord before editing it, so the IP never has to be kept in D1.
Browser storage
What's included
Worker (
tracker/)tracker/src/index.ts: the two routes,POST /visitandPOST /events. Anything else gets a 404https://ml3labs.com, or from a dev server when dev visits are on. Each address may send 60 of each beacon a minute. Bodies over 64 KiB or that aren't a JSON object are refused, ids must look like ids, and every string from the client is cut to length with backticks stripped so it can't break the post's formatting/visit: claims the visit, numbers the browser (a new number on its first visit, one more visit after that, atomic even when two tabs open at once), posts the embed and keeps its message id. Crawlers are skipped. If Discord rejects the post, the visit is still recorded/events: keeps only well-formed page and link events (links must behttp(s):ormailto:), orders them by time, works out time on each page and total duration from the client's own clock, and edits the postthread_id, for example) is kept on every call, so the posts can go to a threadtracker/src/embed.ts: the post itself, one maroon embed under the site's name and iconVisitor #N, then· 2nd visit(and so on) for a returning browser, then· devfor test visits/events, then the total time in the field name and one line per page (with time on it) or click:Clicked "…" in the nav / page / footer,Opened … → host,Emailed …tracker/src/beacon.ts: the event format and limits, shared by the site and the Worker so the two can't drift aparttracker/src/ua.ts: browser, OS and device class (desktop, mobile, tablet) from the User-Agent. An iPad that asks for the desktop site is told apart from a Mac by its touch screen, and crawlers are recognisedtracker/wrangler.jsonc: the D1 binding, the rate limiter andDEV_VISITS(off).DISCORD_WEBHOOK_URLis a secret, set withwrangler secret puttracker/package.json: its own dependencies (wrangler, Workers types, TypeScript) and scripts to run it locally, create the tables locally or remotely, deploy and typecheck..dev.vars(the local webhook) is gitignoredDev visits
DEV_VISITSon, the Worker also takes visits from a dev server onlocalhost,127.0.0.1,10.x.x.x,192.168.x.xor*.local, the waysnext.config.tsallows the dev server to be reached. Their posts are marked "dev" and they're counted with the restnpm run devthrough.dev.vars, and off in the deployed Worker unless turned on inwrangler.jsoncSite
src/components/Tracker.tsx: a client component that renders nothingNEXT_PUBLIC_TRACKER_URLis unset. Anything that throws (blocked or full storage, a browser without beacons) just stops the tracking, never the pagegetRandomValueswhererandomUUIDisn't available (a plain-http address on the local network)src/app/layout.tsx: mounts<Tracker />in the root layout, so it is on every pageDeploy and tooling
.github/workflows/deploy.yaml: the build step getsNEXT_PUBLIC_TRACKER_URLfrom the repository variableTRACKER_URL. While that is unset the site tracks nothingtsconfig.jsonexcludestracker/(it has its own, with Workers types), and ESLint and Prettier ignore the Worker's local.wrangler/output