Implement email verification links
Verify an email address with a signed, expiring link made with an HMAC, so you need no database table for pending verifications.
A verification link only needs to prove that you issued it for this address, recently. An HMAC over the address and an expiry time does that without storing anything.
import { createHmac, timingSafeEqual } from 'node:crypto';
const SECRET = process.env.LINK_SECRET;
const sign = (payload) => createHmac('sha256', SECRET).update(payload).digest('base64url');
export function makeLink(email, ttlMs = 24 * 60 * 60 * 1000) {
const payload = `${email}|${Date.now() + ttlMs}`;
const token = Buffer.from(payload).toString('base64url');
return `https://example.com/verify?t=${token}&s=${sign(payload)}`;
}
export function checkLink(token, sig) {
const payload = Buffer.from(token, 'base64url').toString();
const [email, expires] = payload.split('|');
const good = Buffer.from(sign(payload));
const given = Buffer.from(String(sig));
const valid = good.length === given.length && timingSafeEqual(good, given);
return valid && Number(expires) > Date.now() ? email : null;
}Changing the email or the expiry changes the signature, so a user cannot extend a link or reuse it for another address. The secret never leaves the server, and timingSafeEqual keeps the comparison constant-time. See crypto.createHmac.
A signed link can be used more than once until it expires, which is harmless for verification as long as marking the address verified is idempotent. For a password reset, store a one-time token instead.