OSS · OPEN SOURCE · 2026

track-email-template

Lightweight Cloudflare Workers + D1 email open-tracking pixel and stats template

JavaScript · Cloudflare Workers · D1

GitHub | Release v0.2.0

track-email-template v0.2.0 Cloudflare Workers, D1 schema, and HMAC-SHA256 edge tracking showcase

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.

Dogfooded in Production: This exact edge architecture powers signed outbound link tracking for this portfolio via a dedicated tracking worker, proving the template's real-world simplicity and reliability.

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 + sig parameters) 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.
Security Boundary: Signed URL parameters prevent arbitrary open-redirect abuse while keeping edge verification stateless and fast before recording analytics to D1.

SDLC & Quality Practices

Even a compact utility template benefits from disciplined engineering boundaries:

  1. Stateless Edge Verification + Durable Storage: Separates fast request validation at the Worker boundary from structured SQL event logging in D1.
  2. Clean Template Maintainability: Avoids bloated build toolchains by using straightforward JavaScript compatible with standard Workers deployment workflows.
  3. 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 by STATS_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 new clicks D1 table, send a first-click alert via WEBHOOK_URL, and redirect (302) to the destination URL.

2. Unopened Follow-Up Reminders (Daily Cron Trigger)

  • Added triggers.crons: ["0 9 * * *"] and a scheduled() handler that checks sent_emails older than FOLLOWUP_DAYS (default 4) with zero non-sender-echo opens and zero clicks.
  • Sends one follow-up reminder via WEBHOOK_URL and marks reminded_at in D1 so each application is reminded only once.

3. Interactive Telegram Bot Commands (POST /telegram-webhook)

  • Added /telegram-webhook (authorized against the configured chat_id) supporting:
    • /recent — last 5 sent emails with open and click counts
    • /unopened — sent emails with 0 non-sender-echo opens and 0 clicks
    • /stats <tag> — detailed breakdown for a specific tag

4. High-Interest Re-open Alerts & Proxy Detection

  • Added YahooMailProxy (yahoo-proxy) alongside gmail-proxy, apple-prefetch, scanner, and sender-echo.
  • Added a second alert when non-sender-echo opens reach 3 (High interest (3 opens)), helping spot internal forwarding.

5. Searchable Dashboard & CSV Export (GET /dashboard)

  • Added instant client-side search/filtering, a Clicks column, and a one-click Export CSV button (GET /dashboard?format=csv).

Upgrade Notes (from v0.1 / v0.2)

  • Run npm run db:migrate:remote (or ALTER TABLE sent_emails ADD COLUMN reminded_at TEXT; + schema.sql for existing databases).
  • Run npm run deploy and optionally register /telegram-webhook via Telegram's setWebhook API.

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 or 302 redirect while deferring D1 inserts and webhook notifications to ctx.waitUntil(...).
  • Client & Proxy Classification (classifyClient): Inspects the User-Agent header (truncated to 300 characters) and categorizes traffic into gmail-proxy (GoogleImageProxy), yahoo-proxy (YahooMailProxy), apple-prefetch (AppleMailPrivacyProtection or Mozilla/5.0 + CFNetwork), scanner (empty UA or bot/crawler/preview regex), or human. Opens arriving within 15_000 ms (ECHO_WINDOW_MS) of sent_at are reclassified as sender-echo to 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-echo open, 3rd non-sender-echo open (HIGH_INTEREST_THRESHOLD = 3), 1st click per tag, and daily unopened follow-up sweeps (FOLLOWUP_DAYS, default 4).

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) require STATS_TOKEN via Authorization: Bearer <token> or ?token=<token>.
  • Open-Redirect Prevention: GET /c/<tag> enforces http(s):// scheme validation and verifies the Web Crypto HMAC-SHA256 signature over ${tag}:${targetUrl} keyed by STATS_TOKEN, returning 403 Forbidden for tampered or unsigned URLs.
  • Input & Output Hardening: Tags are constrained to ^[a-zA-Z0-9_-]{1,64}$, User-Agent strings are capped at 300 characters, all D1 queries use parameterized .bind(...) statements, /dashboard escapes HTML via escHtml(), and CSV export quotes and escapes cells via csvCell().
  • Telegram Chat Isolation: /telegram-webhook silently ignores updates ({"ok": true}) unless message.chat.id matches the configured TELEGRAM_CHAT_ID or WEBHOOK_URL chat_id.