You do not need an analytics platform to know whether a client read the proposal you sent. You need four events, one table, and about 150 lines of code. That is the whole system, and it is worth building because the alternative — installing a general-purpose tracker on a client-facing document — gives you a hundred numbers and none of the answers you wanted.
This is a walkthrough of how I built tracked document links: unguessable URLs, optional password gates, event capture that cannot be trusted blindly, and the aggregations that turn raw rows into "they read the pricing twice and stopped before the timeline".
It is a small-system design piece, so it applies to a proposal tool, a contract, an invoice, a shared report, or any page where "did they look at it" is the question.
Start from the four events
Most tracking implementations fail by over-collecting. If you can answer these four questions, you have everything a follow-up needs:
- Was the document opened at all?
- When was it last opened, and how many distinct sessions?
- How far into the document did the reader get?
- Did they make a decision (select a package, approve, decline, ask a question)?
That maps to one append-only table:
CREATE TABLE doc_events (
id INTEGER PRIMARY KEY AUTOINCREMENT,
doc_id TEXT NOT NULL,
event TEXT NOT NULL, -- open | section | decision | question
target TEXT, -- section key, package id, question id
visitor_id TEXT, -- random, per browser, per document
created_at INTEGER NOT NULL, -- server unix ms, never the client's
idem_key TEXT UNIQUE -- dedupes retries
);
CREATE INDEX doc_events_doc_time ON doc_events (doc_id, created_at);
Five columns of payload, one of them a foreign key you enforce in application code. No user agent, no full IP, no referrer, no screen size. You will not use them, and they turn a small feature into a compliance question.
The UNIQUE on idem_key is the piece people skip, and it is the reason their dashboards report 41 opens for one client. More on that below.
Unguessable URLs are a design problem, not a random call
A public document link is a capability URL: whoever holds it can read the document. That has three consequences.
The slug must be unguessable. Not proposals/142, not proposal-acme, not a hash of the client's email. A 128-bit random value encoded compactly is plenty:
function slug(bytes = 16): string {
const buf = crypto.getRandomValues(new Uint8Array(bytes));
// URL-safe base32-ish alphabet, no vowels, no ambiguous chars
const A = '23456789abcdefghjkmnpqrstuvwxyz';
let out = '';
for (const b of buf) out += A[b % A.length];
return out;
}
Using a restricted alphabet is a small courtesy: slugs get read aloud on phone calls and typed from screenshots. Dropping 0/o/1/l/i costs you a few bits and saves support time.
It must not be enumerable through error behaviour. A wrong slug and an archived slug should both return the same 404 page, with the same timing. Otherwise you have built an oracle for "does this client exist on this platform".
It must be revocable without deleting the document. A revoked_at column that the public route checks is cheaper than teaching users to delete and re-create, and it gives you a clean "this link has been replaced" page.
One more decision: make the slug case-insensitive on lookup (store lowercase, normalise input) because clients will re-type it from a printed page in caps.
Optional passwords, hashed properly
Some documents should not be readable by anyone who finds the link in a forwarded email. Password protection is one checkbox and a fair amount of care:
- Store a hash, never the password, and hash with a slow KDF. In a Worker,
crypto.subtle.deriveBitswith PBKDF2-SHA256 at a few hundred thousand iterations is available without dependencies. - Compare in constant time.
crypto.subtle.timingSafeEqualexists in modern runtimes; if it does not, compare HMACs of both values rather than raw strings. - Rate-limit attempts per document and per IP, and count failures in the same counter you use for everything else.
- Put the unlocked state in a short-lived signed cookie scoped to that document path — not in
localStorage, which every script on the page can read.
const bits = await crypto.subtle.deriveBits(
{ name: 'PBKDF2', salt, iterations: 210_000, hash: 'SHA-256' },
await crypto.subtle.importKey('raw', enc.encode(password), 'PBKDF2', false, ['deriveBits']),
256,
);
And a warning that belongs in the product, not just the docs: a password protects against casual forwarding, not against a determined reader who can screenshot. Say so in the UI.
Capturing events without slowing the page
The most common mistake is a blocking fetch on every scroll event. The second most common is capturing nothing on the way out, because the browser is closing the tab.
Two browser APIs do most of the work:
// Beacon on unload-ish moments. Fires even if the page is closing.
navigator.sendBeacon('/api/t/d', new Blob([JSON.stringify(batch)], {
type: 'application/json',
}));
// Same idea with fetch, where sendBeacon is unavailable.
fetch('/api/t/d', {
method: 'POST',
keepalive: true,
headers: { 'content-type': 'application/json' },
body: JSON.stringify(batch),
});
Batch events in memory and flush on a 10-second timer, on visibilitychange to hidden, and on pagehide. A batch is a handful of small objects, so one request covers a whole reading session.
On the server, treat the payload as hostile:
-
Ignore any timestamp the client sends. Stamp
created_atserver-side. Client clocks are wrong, and a wrong clock will silently break every "last opened" query. - Validate the event name and target against an allowlist. Otherwise your table becomes a free-form message board.
-
Derive
doc_idfrom the slug in the URL, not from the body. A client-supplied document id is an invitation to write events into someone else's document. - Rate-limit per document and per visitor id. A public endpoint that writes rows is a target.
Deduplication, because networks lie
Mobile networks retry. Beacons get sent twice. Users open the same link in three tabs. Without deduplication, your "opened 6 times" is really "opened twice and retried four times".
Give every event a client-generated idempotency key — a random string per event, not per batch — and let the unique constraint do the work:
await db.prepare(
`INSERT OR IGNORE INTO doc_events (doc_id, event, target, visitor_id, created_at, idem_key)
VALUES (?, ?, ?, ?, ?, ?)`
).bind(docId, ev.event, ev.target ?? null, visitorId, Date.now(), ev.key).run();
A session is then a derived concept, not a stored one: events grouped by visitor_id with gaps over 30 minutes split into separate sessions. You can change that threshold later without migrating anything.
Section reach, cheaply
"How far did they read" sounds like it needs scroll-depth tracking and a heatmap. It needs one IntersectionObserver on the section headings:
const reached = new Set<string>();
const seen = new Map<string, number>();
const io = new IntersectionObserver((entries) => {
for (const e of entries) {
if (!e.isIntersecting) continue;
const key = (e.target as HTMLElement).dataset.section!;
reached.add(key);
seen.set(key, (seen.get(key) ?? 0) + 1);
queue({ event: 'section', target: key, key: crypto.randomUUID() });
}
}, { rootMargin: '0px 0px -40% 0px' });
for (const el of document.querySelectorAll('[data-section]')) io.observe(el);
The negative bottom margin is the important detail: a section counts as reached when the reader is genuinely in it, not when it first touches the bottom of the viewport. Without it, fast scrolling marks everything as read and the data becomes useless.
This also gives you the two most actionable signals in the whole product:
- Where reading stops. If most readers never reach the timeline, the timeline is not the problem — the section before it is.
- What gets expanded. If three readers open the same FAQ, that answer should move out of the FAQ and into the body of the document.
Turning rows into something a human reads
Raw events are not a dashboard. One aggregate query per document is enough:
SELECT
COUNT(DISTINCT visitor_id) AS visitors,
SUM(CASE WHEN event = 'open' THEN 1 ELSE 0 END) AS opens,
MAX(created_at) AS last_seen,
GROUP_CONCAT(DISTINCT CASE WHEN event = 'decision' THEN target END) AS decisions
FROM doc_events
WHERE doc_id = ?1 AND created_at > ?2;
Then two derived numbers worth showing:
- Section depth: the furthest section key, mapped to its index in the document's own section order. "Reached Pricing" is meaningful to the freelancer; "scrollTop 1840" is not.
- Time on the document: sum of session durations, capped. A tab left open overnight is not engagement, and showing "4h 12m" makes the whole feature look broken.
What not to show: a live feed of every click, a "hot lead" score, or a notification when the client opens the page. That last one is the fastest way to make a client feel watched. If you must notify, notify once, with a delay, and never with a timestamp the client could correlate to their own session.
Retention is part of the schema
The trap with hosted documents is assuming they live forever. They do not: plans change, storage costs money, and a document that was true in March is a liability in December.
The design that has held up:
- The document is rented; the client record is owned. The CRM row survives when the document expires, because the relationship is not the file.
-
Expiry is a column, not a cron-only concept.
expires_atdrives the public route, so an expired link returns a clear page rather than a 500 when the cleanup job has not run. - A PDF is sent before deletion. Not as a courtesy — as the escape hatch that makes deletion acceptable in the first place.
- Deletion cascades, including events. Orphaned analytics on a deleted document is the kind of data you do not want to explain later.
In a Worker, the cleanup is a cron trigger running one statement per table; the interesting part is the email that goes out a week before, not the code that deletes.
The pitfalls that eat a weekend
| Symptom | Cause | Fix |
|---|---|---|
| Opens far higher than real readers | Email security scanners and chat link previews fetch URLs | Treat a request without a JS beacon follow-up (or with a known scanner agent) as not a reader |
| Every event has the same timestamp | Client clock used instead of server time | Stamp server-side, always |
| Duplicates on flaky networks | No idempotency key |
UNIQUE on a client-generated key |
| Mobile sessions look 4 seconds long |
sendBeacon fired on beforeunload, which iOS may skip |
Flush on visibilitychange to hidden as well |
| Events attributed to the wrong document |
doc_id read from the payload |
Derive it from the slug |
| "4h 12m on the document" | Background tab counted as reading | Cap session duration; split on 30-minute gaps |
That first row is the one that surprises people. A large share of "opens" on any link sent by email are machines pre-fetching it. If you do not separate a fetch from a reader, your most-engaged client is a spam filter.
What this costs to run
Four events per session, a few sessions per document, a handful of documents per client. This is a rounding error next to the static assets it serves, and it fits comfortably in a single SQLite-backed edge database with an index on (doc_id, created_at). The public document route can be cached at the edge; the tracking endpoint cannot, and should be the only uncached thing in the system.
The honest limits
- You cannot tell who is reading, only that someone is. A forwarded link looks identical to the client reading it. Do not pretend otherwise in the UI.
- Reading time is a proxy, not attention. Someone reading on a train with the page open and their phone in their pocket will beat your best client on every metric.
- Tracking is not a substitute for a decision. The useful output is a better sentence in your next message, not a score.
- Privacy rules still apply. Event data on a client document is personal data in most jurisdictions. Know your retention window before you collect the first row.
The takeaway
You need four events, a unique key, server timestamps, and a slug nobody can guess. Everything else is presentation. If you keep the schema small and honest, the tracking becomes a feature clients never notice — which is exactly what you want from it.
I build Revercue, which treats proposals, contracts, forms and invoices as tracked links on one client thread, with a free plan you can try on a real client without a card. The tracking is deliberately boring: four events, a section depth, and a decision. If you have built something similar differently, I would like to compare notes on the dedupe strategy.
Top comments (0)