Skip to content
jshacks.dev
Security

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.

1 min read
Summarize in AI

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.

verify.jsJavaScript
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.

Share

More snippets

Security

Report CSP violations to an endpoint

Receive Content Security Policy violation reports at an endpoint with the report-to and report-uri directives, and parse what the browser sends.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.