Two Doors Into One Account: Email Links and Verification Codes
Two Doors Into One Account: Email Links and Verification Codes Passwordless login looks like a solved problem until you watch a real reader try to use it. I built email login for a small membership site and shipped the
Two Doors Into One Account: Email Links and Verification Codes
Passwordless login looks like a solved problem until you watch a real reader try to use it. I built email login for a small membership site and shipped the obvious version first: a magic link. Within a week, half the support messages were about the link, and almost none of them were about broken code.
The link worked. The problem was where it landed. Readers read email on a phone, tap the link, and the browser that opens is not the one where they started. On desktop, the mail client hands the URL to the default browser, which may not be the one holding the half-filled form. The session exists, but not where the reader was.
So the login email now carries two credentials for the same account: a six-digit code that keeps the reader in place, and a one-time link for the case where switching browsers is fine. This article is about how those two paths share one account model without creating two ways to break it.
Why both, and not just the better one
I tried to pick a winner and could not, because the two paths fail in opposite situations.
| Situation | Code | Link |
|---|---|---|
| Reader is on the same device | Types six digits, stays on the page | Opens a new tab, old tab loses its place |
| Reader started on desktop, reads mail on phone | Painful but works | Useless, wrong device |
| Email client opens links in an in-app browser | Irrelevant | Session lands in a browser with no other cookies |
| Autofill or password manager | Not applicable | Copy-paste a long URL is error-prone |
| Reader wants to log in on a second device | Requires the other device | Works |
The pattern that survived: send one email, put the code at the top and the link below it, and let the reader choose. Both derive from the same token row, both expire, both are single-use.
A second decision mattered as much: the email is not a generic "click here to log in". It says what it is, how long each credential lasts, and what to do if the reader did not request it. That sentence cut the "did I get hacked" emails to zero.
One row, two representations
The code and the link are different encodings of one authorization to log in. Storing them as one row keeps expiry and consumption logic in one place.
CREATE TABLE login_tokens (
id INTEGER PRIMARY KEY,
user_id INTEGER NOT NULL,
token_hash TEXT NOT NULL UNIQUE, -- sha256 of the link token
code_hash TEXT NOT NULL, -- sha256 of the six-digit code
attempts INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL,
expires_at TEXT NOT NULL, -- 15 minutes
used_at TEXT, -- NULL until consumed
used_via TEXT -- 'code' or 'link'
);
Two rules come out of this shape:
-
Never store either credential in plaintext. Both are bearer tokens; a database read should not hand someone a login.
sha256is enough here because the input space is bounded by expiry and attempt limits, and because the value is random, not user-chosen. - The code has its own expiry. Ten minutes for the digits, fifteen for the link. Readers copy digits from a notification preview long after the email arrives; giving the link a longer window costs nothing as long as it is single-use.
Minting both at once:
const linkToken = crypto.randomBytes(32).toString('base64url');
const code = String(crypto.randomInt(0, 1_000_000)).padStart(6, '0');
const now = Date.now();
await db.run(
`INSERT INTO login_tokens
(user_id, token_hash, code_hash, created_at, expires_at)
VALUES (?, ?, ?, ?, ?)`,
[userId, sha256(linkToken), sha256(`${userId}:${code}`), iso(now), iso(now + 15 * 60_000)]
);
The code hash includes user_id. Without it, six digits collide constantly across accounts and one lookup could match several rows. With it, the composite input is unique per account.
The link carries the raw token: https://example.com/api/auth/magic-login?token=<linkToken>. The code is typed into a field on the page that asked for it.
Consuming once, under concurrency
Single-use is easy to say and easy to get wrong. A read-then-write leaves a window:
const row = await db.get('SELECT * FROM login_tokens WHERE token_hash = ?', [hash]);
if (!row || row.used_at) return reject();
await db.run('UPDATE login_tokens SET used_at = ? WHERE id = ?', [now, row.id]);
Two requests interleaved between SELECT and UPDATE both pass the check. Make the update the test:
const consumed = await db.run(
`UPDATE login_tokens
SET used_at = ?, used_via = ?
WHERE token_hash = ?
AND used_at IS NULL
AND expires_at > ?`,
[iso(Date.now()), via, hash, iso(Date.now())]
);
if (consumed.changes !== 1) return reject('invalid_or_expired');
The database decides. One statement, one row, one winner. The same statement enforces expiry, so there is no window where a token is valid but the code thinks it is not.
used_via exists for one reason: when a reader writes in saying the link "didn't work", I can tell whether the scanner ate it or the code path won the race.
The failure mode I did not anticipate
Email security scanners open links before the reader does. Corporate mail gateways, link-checking features in mail clients, and preview bots all issue a GET to see whether the URL is dangerous. My first implementation created a session on that GET.
The reader then opened the link and got "this link has already been used". Technically correct, practically infuriating, and impossible to explain in a support reply.
Three options, in order of how much I like them:
-
Two-step confirmation. The link lands on a page with one button, and the session is created by a
POST. Scanners do not submit forms. Cost: one extra tap and a page that must not be cached. -
Grace for a second use from a different client. Store
used_atand allow one more consumption within sixty seconds if the user agent differs. Cost: a second window to reason about. - Prefer the code, document the link as best-effort. Cost: the link occasionally burns itself, and the reader types digits.
I shipped option 3 and wrote option 1 into the next iteration, because a confirmation page is honest: it tells the reader a login is about to happen. If you are building this today, start with option 1.
Who is allowed to receive the email
An email-sending endpoint is an abuse surface, not just a login form. Two controls:
-
Policy gate. A single setting decides which account states can receive mail at all:
subscriber, meaning subscribed, pending review, or approved. Anyone else gets a neutral response. This turns a paid feature's login into a support channel only for people who already have a relationship with the site. - Neutral responses. The endpoint returns the same body and status whether the address exists, is blocked, or just received an email. No enumeration, no "user not found".
Rate limiting lives outside the token table: per email address and per IP, with a short window. A second request inside the window does not mint a new code; it invalidates nothing and returns "check your inbox". Minting a fresh code on every request would let an attacker brute-force six digits by flooding the reader with new ones.
The next parameter is an open redirect waiting to happen
Both paths accept a destination so the reader returns to the page that needed login. That parameter is attacker-controlled and will be used for phishing if it is not constrained.
The rule I use is small and easy to test:
function safeNext(raw) {
if (!raw || typeof raw !== 'string') return '/';
if (!raw.startsWith('/')) return '/'; // no absolute URLs
if (raw.startsWith('//')) return '/'; // protocol-relative
if (raw.includes('\\')) return '/'; // backslash tricks
if (raw.includes('://')) return '/';
return raw.slice(0, 200);
}
Note what it does not do: it does not try to parse and normalize. It rejects anything that is not obviously a site-relative path, and falls back to the home page. Whitelisting beats blacklisting for a value this small.
When the destination is handed to the client, encode it once. Double-encoding a query string inside next produces a link that looks right in the email and arrives at the server mangled, which reads as "the link is broken" and sends you looking in the wrong place.
Session shape
Both paths end in the same session, so downstream code never asks how the reader got in.
res.cookie('session', sid, {
httpOnly: true,
secure: true,
sameSite: 'Lax',
maxAge: 7 * 24 * 60 * 60 * 1000,
path: '/'
});
-
httpOnlyso a page script cannot read it. -
SameSite=Laxrather thanStrict, because the link arrives from a mail client as a cross-site navigation.Strictwould drop the cookie on exactly the path that needs it. - Seven days, not thirty. A membership site is not a bank, but it is also not a place where a forgotten cookie should live for a month.
Sessions are server-side rows, not signed cookies. Revocation has to be possible without rotating a secret that invalidates everyone.
Leakage is worth one line of defense: the token appears in a URL, so set Referrer-Policy: strict-origin-when-cross-origin on the site and avoid third-party scripts on the endpoint that consumes it. Once the token is spent, the URL in a reader's history is harmless.
What this bought
- Support messages about login dropped to near zero, and the ones that remained were about the six-digit code arriving late, which is a mail deliverability question rather than a design bug.
- One token table, one consumption statement, two entry points. Adding a third path later would mean another column, not another flow.
- The email explains itself, which removed the "was this you" traffic entirely.
If I were starting over, I would ship the confirmation page for the link on day one. Everything else here I would keep: hash both credentials, let the database decide single-use, constrain next to site-relative paths, and make the email say what it is.
This article describes the email login flow on wuhuajin.com, where membership articles are protected by a small API rather than a full identity provider. The implementation sends one email with a short code and a one-time link, stores only hashes, and treats the database update as the single source of truth for whether a credential was used.
Originally published on wuhuajin.com.
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.