Skip to content

feat(tracker): post each visit to discord through a cloudflare worker - #3

Merged
dark-sorceror merged 5 commits into
mainfrom
feat/visitor-tracker
Oct 28, 2026
Merged

dark-sorceror merged 5 commits into
mainfrom
feat/visitor-tracker

Conversation

@dark-sorceror

Copy link
Copy Markdown
Member

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 unless NEXT_PUBLIC_TRACKER_URL is set.

How it works

Visit starts (first page load in a tab)
  → site beacons /visit: visit id, browser id, entry page, referrer, language
    → Worker checks the origin and the rate limit, skips crawlers
      → claims the visit id in D1 (a repeat is ignored)
        → numbers the browser in one batch (visitor number + visit count)
          → adds city, region, country, time zone and network from request.cf,
            browser / OS / device from the User-Agent
            → posts ONE Discord embed through the webhook, keeps its message id

As the visit goes on, the site keeps each page reached and each link clicked in sessionStorage

Tab hides (leaving, switching tabs, opening another site) or an email link opens
  → site beacons /events: visit id, pages and clicks so far
    → Worker cleans the events and skips a repeat of the last beacon
      → reads the post back from Discord and edits only its Session field:
        each page with its time, each click
        → saves the events and the visit's duration to D1

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 /visit again, 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 sendBeacon as text/plain JSON, 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 is IF NOT EXISTS)

  • counters: the running visitor number
  • visitors: 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 seen
  • sessions: 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 time

No 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

  • localStorage: the browser id, kept across visits
  • sessionStorage: the visit id and the events so far (the first event and the newest, 100 at most)

What's included

Worker (tracker/)

  • tracker/src/index.ts: the two routes, POST /visit and POST /events. Anything else gets a 404
    • Visits come from https://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 be http(s): or mailto:), orders them by time, works out time on each page and total duration from the client's own clock, and edits the post
    • The webhook's query string (a thread_id, for example) is kept on every call, so the posts can go to a thread
  • tracker/src/embed.ts: the post itself, one maroon embed under the site's name and icon
    • Title: Visitor #N, then · 2nd visit (and so on) for a returning browser, then · dev for test visits
    • Fields: Location (city, region, country, and the visitor's local time), Network (provider and AS number, with the IP on desktop), Device (browser and OS), Language, Entry page, Referrer (its hostname as a link, or "Direct")
    • Session: "Tracking (has not left the site yet)…" until the first /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 …
    • Discord rejects fields over 1024 characters, and a rejected edit leaves the post stuck, so long sessions keep the newest lines and note how many earlier ones were left out. A referrer is escaped so it can't add a link of its own, and shows as its host alone if it would run too long
  • tracker/src/beacon.ts: the event format and limits, shared by the site and the Worker so the two can't drift apart
  • tracker/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 recognised
  • tracker/wrangler.jsonc: the D1 binding, the rate limiter and DEV_VISITS (off). DISCORD_WEBHOOK_URL is a secret, set with wrangler secret put
  • tracker/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 gitignored
  • Tests for the session lines, the field trimming, the referrer escaping and the User-Agent parsing

Dev visits

  • With DEV_VISITS on, the Worker also takes visits from a dev server on localhost, 127.0.0.1, 10.x.x.x, 192.168.x.x or *.local, the ways next.config.ts allows the dev server to be reached. Their posts are marked "dev" and they're counted with the rest
  • It's on for npm run dev through .dev.vars, and off in the deployed Worker unless turned on in wrangler.jsonc

Site

  • src/components/Tracker.tsx: a client component that renders nothing
    • Off when NEXT_PUBLIC_TRACKER_URL is unset. Anything that throws (blocked or full storage, a browser without beacons) just stops the tracking, never the page
    • Starts the visit once per tab, records each page as it is reached and each link clicked (its words or aria-label, where it goes, and whether it sat in the nav, the page or the footer)
    • Sends the events when the tab hides, and right away when an email link opens another app and leaves the page showing
    • Ids fall back to getRandomValues where randomUUID isn'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 page

Deploy and tooling

  • .github/workflows/deploy.yaml: the build step gets NEXT_PUBLIC_TRACKER_URL from the repository variable TRACKER_URL. While that is unset the site tracks nothing
  • tsconfig.json excludes tracker/ (it has its own, with Workers types), and ESLint and Prettier ignore the Worker's local .wrangler/ output

@dark-sorceror
dark-sorceror merged commit 32589d5 into main Oct 28, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant