OSS · OPEN SOURCE · 2026
track-email-template
Lightweight Cloudflare Workers + D1 email open-tracking pixel and stats template
JavaScript · Cloudflare Workers · D1

Overview / Engineering Problem
Tracking outbound email opens and link engagement typically pushes teams toward heavyweight marketing platforms or third-party SaaS trackers that collect user data across unrelated domains. For developers and small teams wanting self-hosted, minimal-footprint telemetry, spinning up a full VPS and database server solely for pixel and redirect endpoints is excessive.
track-email-template provides a lightweight, open-source Cloudflare Workers + D1 template in JavaScript for serving email open-tracking pixels, handling signed click-redirect links, and exposing analytics statistics endpoints directly at the edge.
Architecture & Technical Decisions
The template takes advantage of Cloudflare's serverless edge runtime and embedded SQLite database:
- Edge Request Handling (Cloudflare Workers): Serves ultra-fast tracking pixel responses and link redirects from edge locations in JavaScript with zero server maintenance or container provisioning.
- Serverless SQL Persistence (Cloudflare D1): Logs open events, click redirects, and campaign/link identifiers directly into Cloudflare D1, enabling clean SQL aggregation for analytics stats endpoints without managing external database clusters.
- Signed Redirect Links: Supports cryptographic signature verification on outbound redirect URLs (
url+sigparameters) so redirect endpoints cannot be abused as open relays. - Minimal Template Footprint: Intentionally kept lean and forkable at arousi/track-email-template so developers can customize schemas, routes, and stats queries in minutes.
SDLC & Quality Practices
Even a compact utility template benefits from disciplined engineering boundaries:
- Stateless Edge Verification + Durable Storage: Separates fast request validation at the Worker boundary from structured SQL event logging in D1.
- Clean Template Maintainability: Avoids bloated build toolchains by using straightforward JavaScript compatible with standard Workers deployment workflows.
- Open-Source Reusability: Released publicly so teams maintain full ownership over their telemetry data without third-party SaaS lock-in.
Stack & Deliverables
| Layer | Technology / Artifact | Role in System |
|---|---|---|
| Edge Runtime | Cloudflare Workers (JavaScript) | Open-tracking pixel delivery, signed redirects, and stats API |
| Edge Database | Cloudflare D1 | Serverless SQLite persistence for open and click analytics |
| Template Repo | GitHub (arousi/track-email-template) |
Forkable open-source starter for self-hosted email telemetry |
Latest Release: v0.2.0 (v0.2.0)
What's Changed in v0.2.0
1. HMAC-Signed Click-Tracking Redirects (POST /sign-link & GET /c/<tag>)
- Added
POST /sign-link(protected bySTATS_TOKEN) to generate HMAC-SHA256 signed tracking URLs (/c/<tag>?url=...&sig=...). - Added
GET /c/<tag>to verify the signature (preventing open-redirect abuse), log clicks in the newclicksD1 table, send a first-click alert viaWEBHOOK_URL, and redirect (302) to the destination URL.
2. Unopened Follow-Up Reminders (Daily Cron Trigger)
- Added
triggers.crons: ["0 9 * * *"]and ascheduled()handler that checkssent_emailsolder thanFOLLOWUP_DAYS(default4) with zero non-sender-echoopens and zero clicks. - Sends one follow-up reminder via
WEBHOOK_URLand marksreminded_atin D1 so each application is reminded only once.
3. Interactive Telegram Bot Commands (POST /telegram-webhook)
- Added
/telegram-webhook(authorized against the configuredchat_id) supporting:/recent— last 5 sent emails with open and click counts/unopened— sent emails with 0 non-sender-echoopens and 0 clicks/stats <tag>— detailed breakdown for a specific tag
4. High-Interest Re-open Alerts & Proxy Detection
- Added
YahooMailProxy(yahoo-proxy) alongsidegmail-proxy,apple-prefetch,scanner, andsender-echo. - Added a second alert when non-
sender-echoopens reach 3 (High interest (3 opens)), helping spot internal forwarding.
5. Searchable Dashboard & CSV Export (GET /dashboard)
- Added instant client-side search/filtering, a
Clickscolumn, and a one-click Export CSV button (GET /dashboard?format=csv).
Upgrade Notes (from v0.1 / v0.2)
- Run
npm run db:migrate:remote(orALTER TABLE sent_emails ADD COLUMN reminded_at TEXT;+schema.sqlfor existing databases). - Run
npm run deployand optionally register/telegram-webhookvia Telegram'ssetWebhookAPI.
Architecture Overview
track-email-template runs as a single zero-dependency Cloudflare Worker (src/index.js, type: module) backed by Cloudflare D1 (DB binding, email-tracker-db), custom domain TLS routing (custom_domain: true), and a daily Cron Trigger (0 9 * * *).
- Non-Blocking Edge Telemetry (
ctx.waitUntil): Open pixel (GET /p/<tag>.png) and click redirect (GET /c/<tag>) handlers immediately return the 67-byte 1×1 transparent PNG or302redirect while deferring D1 inserts and webhook notifications toctx.waitUntil(...). - Client & Proxy Classification (
classifyClient): Inspects theUser-Agentheader (truncated to 300 characters) and categorizes traffic intogmail-proxy(GoogleImageProxy),yahoo-proxy(YahooMailProxy),apple-prefetch(AppleMailPrivacyProtectionorMozilla/5.0+CFNetwork),scanner(empty UA or bot/crawler/preview regex), orhuman. Opens arriving within15_000ms (ECHO_WINDOW_MS) ofsent_atare reclassified assender-echoto suppress self-open alerts. - Multi-Provider Webhook Alerts (
sendWebhookMessage): Automatically formats outbound alerts for Telegram (api.telegram.org), Discord (discord.com/api/webhooks/), or generic JSON webhooks (WEBHOOK_URL). Alerts trigger on the 1st non-sender-echoopen, 3rd non-sender-echoopen (HIGH_INTEREST_THRESHOLD = 3), 1st click per tag, and daily unopened follow-up sweeps (FOLLOWUP_DAYS, default4).
Endpoint Reference
| Method & Path | Auth | Behavior |
|---|---|---|
GET /health |
None | Liveness probe returning {"ok": true}. |
GET /p/<tag>.png |
None | Matches ^/p/([a-zA-Z0-9_-]{1,64})\.png$. Serves a 67-byte 1×1 transparent PNG with Cache-Control: no-store, no-cache, must-revalidate, max-age=0 (Pragma: no-cache, Expires: 0) and logs the open + client_type asynchronously. |
POST /sign-link |
STATS_TOKEN |
Accepts {"tag", "url"} (TAG_RE + http(s)://), signs ${tag}:${targetUrl} with HMAC-SHA256 via crypto.subtle, and returns {"ok": true, "click_url": ".../c/<tag>?url=...&sig=..."}. |
GET /c/<tag>?url=...&sig=... |
HMAC-SHA256 sig |
Matches ^/c/([a-zA-Z0-9_-]{1,64})$. Verifies STATS_TOKEN is configured, url is http(s)://, and sig matches the 32-char hex HMAC-SHA256 digest (400 / 403 on failure). Logs click asynchronously and responds with 302 redirect. |
POST /sent |
STATS_TOKEN |
Accepts {"tag", "recipient", "subject", "sent_at?"} and upserts into sent_emails (ON CONFLICT(tag) DO UPDATE). |
GET /stats[?tag=<tag>] |
STATS_TOKEN |
Queries sent_emails, opens, and clicks in parallel (Promise.all), returning JSON with sent, open_count, human_open_count, click_count, opens, and clicks (latest 50 sent / 100 opens / 100 clicks when unfiltered). |
GET /dashboard[?format=csv] |
STATS_TOKEN |
Renders a searchable HTML table of the latest 150 sent_emails with aggregated open, human-open, and click counts, or downloads email-tracker-export.csv when format=csv. |
POST /telegram-webhook |
Authorized chat_id |
Handles Telegram bot commands /recent, /unopened, and /stats <tag> when message.chat.id matches TELEGRAM_CHAT_ID or the chat_id in WEBHOOK_URL. |
D1 Persistence (schema.sql)
Three SQLite tables with indexed tag lookups (idx_opens_tag, idx_clicks_tag):
sent_emails:id,tag(UNIQUE),recipient,subject,sent_at,reminded_at.opens:id,tag,opened_at,user_agent,client_type(default'unknown').clicks:id,tag,url,clicked_at,user_agent,client_type(default'unknown').
Security Notes
- Token Scoping: All management and analytics endpoints (
/sign-link,/sent,/stats,/dashboard) requireSTATS_TOKENviaAuthorization: Bearer <token>or?token=<token>. - Open-Redirect Prevention:
GET /c/<tag>enforceshttp(s)://scheme validation and verifies the Web Crypto HMAC-SHA256 signature over${tag}:${targetUrl}keyed bySTATS_TOKEN, returning403 Forbiddenfor tampered or unsigned URLs. - Input & Output Hardening: Tags are constrained to
^[a-zA-Z0-9_-]{1,64}$,User-Agentstrings are capped at 300 characters, all D1 queries use parameterized.bind(...)statements,/dashboardescapes HTML viaescHtml(), and CSV export quotes and escapes cells viacsvCell(). - Telegram Chat Isolation:
/telegram-webhooksilently ignores updates ({"ok": true}) unlessmessage.chat.idmatches the configuredTELEGRAM_CHAT_IDorWEBHOOK_URLchat_id.