The device that clicks your magic link isn't the one that needs to log in
The simplest magic link logs you in wherever you click it. That sounds fine until you look at where people actually click. You type your email on your laptop, the link arrives in an app that opens it on your phone, and the session is created on the phone — so the laptop you were working on never logs in at all. The click and the session are assumed to happen in the same browser. Often they don't. This is the flow I ended up with, and why it pulls those apart: clicking the link, proving the link, and creating the session become three separate steps.
The textbook magic link is a single GET handler. The link arrives by email, the user clicks, the handler looks up the token, marks it used, sets a session cookie, and redirects to the dashboard. One request, one round trip, done. It works in development, because in development you click the link in the same browser you requested it from.
Then real delivery happens. A user types their email into the form on their laptop. The link arrives, and they open it on their phone — because that is where their mail is. The single-GET handler dutifully sets a session cookie, but it sets it on the phone's in-app browser. The laptop tab, the one they were actually working in, never learns anything happened. The link worked. It logged in the wrong device.
The same wrongness shows up with corporate mailboxes, for a different reason. Microsoft Defender for Office 365 (Safe Links), Proofpoint URL Defense, and Mimecast rewrite every URL in inbound mail and fetch it to scan what is on the other end. And it is not only enterprise gateways: chat apps unfurl link previews, and browsers prefetch URLs you merely hover over — every one of them issues a GET you never asked for. A single-GET magic link is not idempotent — the first successful request consumes it — so that automated GET burns the link before the human clicks. Different cause, same shape: the request that hits your handler is not the one you meant to log in.
Both failures come from one mistake: the design treats clicking, proving, and session-creating as a single event. They are three events, and they can happen in three different places.
The GET stays pure; clicking only proves the token
The first move is the one constraint that survives from the scanner problem: the GET on the link must be side-effect-free. A scanner that previews the URL has to land somewhere harmless. So GET /auth/<token> does not look up the token, write to the database, or set a cookie. It renders a page and nothing else.
Clojure — routes/auth.clj, handle-auth-confirm
(defn handle-auth-confirm [request token]
;; Step 1 of the consume. Pure presentation — no token lookup,
;; no DB write, no session cookie. Mail-scanner previews land
;; here harmlessly.
{:status 200
:headers {"Content-Type" "text/html; charset=utf-8"
"X-Robots-Tag" "noindex, nofollow"}
:body (confirm-page-html (i18n/lang-from-request request) token)})
The confirm page renders a form that POSTs to /auth/<token>/verify, and a tiny deferred script submits it on load. Scanners GET; they do not execute JavaScript and POST a form to a derived URL, so the side effect only fires in a real browser. But here is the change from the obvious design: that POST does not log anyone in. It marks the token verified, and stops.
SQL — queries/users.clj, verify-magic-token!
UPDATE magic_link_tokens
SET verified_at = now()
WHERE token = ?
AND verified_at IS NULL
AND used_at IS NULL
AND expires_at > now()
RETURNING email
No session is created on the clicking device. Whatever browser opened the link — your phone, an in-app webview, a confirming click — has now done exactly one thing: it has told the server "a human reached this token." The verified_at IS NULL guard is in the same statement that sets verified_at, so re-clicks and double-submits collapse to one winner and the rest return nothing. Clicking proves the token. It does not spend it.
The originating tab claims the session by polling
If clicking the link doesn't create the session, something else has to. That something is the tab the user started in — the laptop tab sitting on the "we sent you a link" page. It finds out the link was proven by polling.
When the user submitted the login form, the server minted a second secret — a poll secret — and set it as an auth-poll-secret cookie scoped to /auth in that browser. It stored only the secret's hash on the token row, as origin_poll_hash. The "sent" page then polls a status endpoint, and the browser sends that cookie automatically.
JavaScript — auth-poll.js (trimmed for length)
function poll() {
if (Date.now() - startedAt >= MAX_MS) { onTimeout(); return; }
fetch('/auth/status', { credentials: 'same-origin' })
.then(function (resp) { return resp.json(); })
.then(function (data) {
if (data && data.status === 'verified') {
stopPolling();
window.location.href = data.next || '/dashboard';
}
// "pending" or anything else: keep polling
})
.catch(function () { /* network/parse error: keep polling */ });
}
intervalId = setInterval(poll, INTERVAL_MS); // 2.5s, capped at the 15-min TTL
The status endpoint is keyed only by that poll-secret cookie. It hashes the cookie value, finds the token row by origin_poll_hash, and checks whether verified_at is set yet. While the link is unproven, it returns a constant {"status":"pending"} — the same response whether the cookie matches no token at all or matches one that hasn't been verified, so a prober can't tell the difference. Once the token is verified, it creates the session in this browser and hands back where to go.
Clojure — routes/auth.clj, handle-auth-status (verified branch, trimmed)
;; row found via origin_poll_hash, verified_at is set:
(let [{:keys [user-agent ip]} (auth/request-meta request)
existing-sid (:origin_session_id row)
session-id (if existing-sid
existing-sid ; already claimed — reuse
(let [{:keys [session-id]} (auth/establish-session!
ds (:email row) user-agent ip)
claimed (q/claim-poll-session! ds hash session-id)]
(or claimed
(:origin_session_id (q/find-token-by-poll-hash ds hash))
session-id)))]
{:status 200
:headers {"Content-Type" "application/json"}
:body (json/write-value-as-string
{"status" "verified" "next" (or next-path "/dashboard")})
;; expire the poll-secret immediately so it can't mint another session
:cookies {"session" (shell/session-cookie session-id)
"auth-poll-secret" (shell/expired-cookie "/auth")}})
The phone proved the token. The laptop created the session for itself, because the laptop is the only browser holding the poll secret. The two events happened on two devices, and each device did only the part it was entitled to do.
The status endpoint must be keyed on the poll secret and never on the emailed token. The token is the thing that travels through the world — it sits in mail servers, gets fetched by scanners, opens on a phone you don't control. The poll secret never leaves the browser that started the login. If you "simplify" by letting the emailed token drive /auth/status, you hand the power to mint a session in a browser to everyone in the mail delivery path. Keep the two credentials separate: the token proves a human reached the link; the cookie proves which browser is allowed to become logged in.
One more reason the token must not be the key to anything cheap: it is hashed at rest. Only the digest reaches disk, so a database leak doesn't hand out working links.
Clojure — queries/users.clj, create-magic-token!
(jdbc/execute-one! ds
["INSERT INTO magic_link_tokens (token, email, expires_at, origin_poll_hash)
VALUES (?, ?, ?, ?)"
(tokens/sha256-hex token) email expires-at origin-poll-hash])
The token itself is 128 bits from a CSPRNG, not a six-digit code. A magic link is single-factor authentication — the link is the credential — so it has to carry enough entropy that guessing it is hopeless, not merely slow.
Polling cuts both ways
The poll design has a dark mirror, and it is worth being honest about. If clicking the link only proves the token, and the browser that ends up logged in is whichever one holds the matching poll secret, then nothing about the mechanism forces that browser to be yours.
Evan Todd lays the attack out as a polling-phishing race. Someone submits your address into the real login form from their browser, so the real service mints the poll secret into their browser and emails you a genuine magic link. If you click it — and it is a real message from a service you actually use — you prove the token, and the attacker's polling tab is the one that gets the session. Nothing on your end looks wrong, because technically nothing is: the mail was real, the link was real, you clicked your own link. You just proved a login someone else started.
The clean structural answer is passkeys, which are not phishable; the login page surfaces registered ones through conditional mediation for exactly this reason. For the magic-link path itself, Todd's mitigation is to put the initiating context — IP, user agent, rough location — into the "is this you?" mail so an unfamiliar origin stands out before you click. What I do today is a weaker, later version of that: I don't gate the click, but for a returning user the first login from an unseen (user-agent, IP) pair sends a notification mail carrying that origin and a one-click revoke link, so a session taken this way can be killed from your inbox. A first-ever login is deliberately silent, which means a brand-new account gets no such warning — the weakest corner of this.
Clojure — auth.clj, new-device-check! (trimmed)
(if (and (q/has-prior-logins? ds user-id)
(q/new-device-excluding? ds user-id ua ip session-id))
;; First sight of this (user-agent, IP) for a returning user:
;; mint a per-session revoke token and mail the origin plus a
;; one-click /auth/revoke/ link.
(let [revoke-secret (tokens/random-urlsafe)]
;; … create-revoke-token! + send-new-device-notification! …
)
;; Otherwise stay silent — first-ever login, or a familiar device.
)
I would rather name the gap than paper over it: this is reactive, not preventive. The attacker holds a real session until you act on the mail, and the warning leans on you noticing an unfamiliar IP. Moving the check in front of the click is the stronger design, and passkeys sidestep the whole class.
Two polls can race — let the database arbitrate
Splitting the work across devices introduces a concurrency hazard the single-GET design never had. The user might have two tabs open on the "sent" page, or the poll might fire twice before window.location.href navigates away. Each call sees verified_at set and rushes to create a session — and now you have minted two sessions for one login.
The wrong fix is to check origin_session_id IS NULL in application code and then write it: two polls can both read "null" before either writes, and both proceed. The fix is to make the claim a single atomic statement, with the guard in the WHERE clause, and let the database decide who won.
SQL — queries/users.clj, claim-poll-session!
UPDATE magic_link_tokens
SET origin_session_id = ?
WHERE origin_poll_hash = ?
AND origin_session_id IS NULL
AND used_at IS NULL
AND expires_at > now()
RETURNING origin_session_id
The first poll to arrive matches the NULL guard, writes its session id, and gets it back from RETURNING. Any concurrent poll no longer matches the guard, touches zero rows, gets a nil RETURNING, and re-reads the row to reuse the winner's session id. The browser ends up with exactly one session regardless of how many polls raced. It is the same single-winner pattern as the verified_at guard above: put the validity condition in the statement that mutates, and the database serializes the writes for you.
Honest about the edge: a losing poll may have already called establish-session! before it lost the claim, leaving an orphan session row. That is bounded and self-cleaning — a small per-user session cap evicts the oldest on the winner's next login — but it is real, and I would rather name it than pretend the claim is perfectly clean.
When there is no originating tab
Not every login has a tab to return to. You might click the link on a brand-new device, or close the laptop tab, or never have had a poll secret in the first place. So the confirm page also carries an explicit "log in on this device" button that POSTs to /auth/<token>/session, consumes the verified token, and creates the session right there. It is never auto-submitted — only the silent verify form is — and the <noscript> fallback shows only this button, so a scripting-disabled browser can still complete a login without ever firing the automatic verify.
That fallback is also why the destination never travels in the URL. After login you usually want to send the user back where they came from — a ?next= path. Putting it in the link or a query string makes it attacker-influenceable and leaks it into history, logs, and Referer. Instead the validated destination rides in a path-scoped cookie set when the form is shown, and it is allowlisted before it is ever trusted.
Clojure — routes/auth.clj, safe-next
(defn safe-next
"Whitelist same-origin landing paths so a `?next=` value cannot be
turned into an open redirect. Accepts paths that start with `/` and
are not protocol-relative (`//host`); returns nil otherwise so
callers can fall back to their default."
[path]
(when (and path
(string? path)
(str/starts-with? path "/")
(not (str/starts-with? path "//")))
path))
The takeaway
If you ship magic links, stop treating the link as a single event. Separate the three things the naive design conflates: clicking the link, proving the link, and creating the session. Let the click prove the token with a side-effect-free GET and a guarded verified_at write. Let the browser that started the login create its own session by polling on a secret only it holds — never on the emailed token, which everyone in the delivery path has touched. Make every state transition a single guarded UPDATE so concurrent requests can't both win. Hash the token at rest, keep a single-device fallback for when there's no tab to return to, and carry the post-login destination in an allowlisted cookie rather than the URL.
None of these pieces is exotic. The trap is that the naive single-GET version passes every test you are likely to write, because your test client clicks the link in the same browser it requested it from. Your users don't. They request on the laptop and click on the phone, and the scanner clicks before either.
Credit where it is due: this whole shape follows two posts by Evan Todd — Magic link pitfalls and More magic link pitfalls. The verify-then-poll flow and the polling-phishing problem both come from there; this post is what they look like in our codebase.