GuidesWeb app
Tutorial: passwordless login with a magic link
1. Send the link
import { randomBytes, createHash } from 'node:crypto';
const token = randomBytes(32).toString('base64url');
const hash = createHash('sha256').update(token).digest('hex');
await db.links.create({ email, hash, expires: Date.now() + 15 * 60_000 });
await sendEmail(email, `https://example.com/login?t=${token}`);
Only the hash is stored: a database leak gives away no valid link.
2. Consume it
- 1Confirmation pageThe link opens a page with a button, consuming nothing.
- 2CheckHash found, not expired, never used.
- 3Single useThe token is deleted at once.
- 4SessionCookie
HttpOnly,Secure,SameSite=Lax.
3. Safeguards
| Risk | Fix |
|---|---|
| Burst of requests | Limit per address and per IP |
| Link intercepted later | Expiry of 10 to 15 minutes |
| Link reused | Deleted on first use |
| Revealing accounts | Same message in every case |
For the sending limit: rate limiting an API. The big picture: building a web app.
Frequently asked questions
- Is it as safe as a password?
- Security rests on the mailbox, just like a password reset. There is no reused or weak password to steal.
- Why is the link already used when I click it?
- Some mail filters open links to scan them. So the link leads to a page with a “Sign me in” button, and that click is what consumes the token.
- Should I say when the address doesn't exist?
- No. Always show the same message (“if an account exists, a link has been sent”) so you don't reveal who is registered.