Prompt
How do I implement passwordless authentication with magic links or OTPs?
Latest observation
Passwordless authentication with magic links or one-time passwords (OTPs) is usually built as a two-step flow:
- User submits an identifier
Usually an email address or phone number. - Server sends a short-lived, single-use secret
- Magic link: a signed token embedded in a URL
- OTP: a short code the user enters back into the app
- User verifies the secret
- Server creates a session
- Usually via an HTTP-only session cookie or token
1) Recommended architecture
Magic link flow
- User enters email
- Server generates a cryptographically secure token
- Token is stored hashed in DB/Redis with:
- user/email
- expiration time
- single-use flag
- Server emails a link like:
https://example.com/auth/verify?token=... - When clicked:
- server validates token
- marks it used
- creates session
- redirects user to app
OTP flow
- User enters email or phone
- Server generates a 6-digit or 8-digit code
- Store hashed code with expiry and attempt count
- Send code via email/SMS
- User enters code
- Server verifies it
- Create session
2) Security requirements
No matter which method you use:
- Use secure random generation
- Magic links: at least 128 bits of entropy
- OTPs: use
crypto.randomInt()or equivalent
- Store tokens/codes hashed, not plaintext
- Expire quickly
- Magic links: 10–30 minutes
- OTPs: 5–10 minutes
- Single-use only
- Rate limit requests and verification attempts
- Prevent account enumeration
- Return the same response whether or not the account exists
- Bind token to context if possible
- optional: device/browser fingerprint, IP range, or user agent
- Use HTTPS only
- Use secure cookies
HttpOnly,Secure,SameSite=LaxorStrict
- Invalidate on new request
- if a new magic link is requested, invalidate previous ones
- Add anti-abuse protections
- CAPTCHA, throttling, email reputation checks, SMS fraud controls
3) Magic link implementation pattern
Database schema example
users
- id
- email
- created_at
login_tokens
- id
- user_id
- token_hash
- expires_at
- used_at
- created_at
- request_ip
- user_agent
Generate token
Use a long random token:
import crypto from "crypto";
const token = crypto.randomBytes(32).toString("hex"); // 64-char token
const tokenHash = crypto.createHash("sha256").update(token).digest("hex");
Send link
const link = `https://example.com/auth/verify?token=${token}`;
Verify
- Hash the incoming token
- Find matching DB record
- Check:
- exists
- not expired
- not used
- Mark used
- Create session
4) OTP implementation pattern
Generate OTP
import crypto from "crypto";
const otp = crypto.randomInt(100000, 1000000).toString(); // 6 digits
Store hashed OTP
const otpHash = crypto.createHash("sha256").update(otp).digest("hex");
Verification rules
- Match the hash
- Enforce expiry
- Limit attempts, e.g. 5 tries
- Invalidate after successful use
UX tip
For email OTPs, auto-focus the input and allow paste handling. For SMS, support auto-fill on mobile where possible.
5) Example flow for email magic links
Request login
POST /auth/request-link
- Input: email
- Always respond: “If that email exists, we sent a link.”
Verify link
GET /auth/verify?token=...
- Validate token
- Create session
- Redirect to app
6) Example flow for email OTP
Request code
POST /auth/request-otp
- Input: email
- Send 6-digit code
Verify code
POST /auth/verify-otp
- Input: email + code
- If valid, create session
7) Session management
After successful login, prefer:
- Server-side session
- Stored in a secure, HTTP-only cookie
Example cookie settings:
HttpOnly: trueSecure: trueSameSite: LaxMax-Age: session duration
If using JWTs, be careful: storing them in localStorage is less secure. A secure cookie-based session is usually better for web apps.
8) Abuse prevention checklist
- Rate limit by:
- IP
- email/phone
- device fingerprint if appropriate
- Cap verification attempts
- Add cooldown between resend requests
- Log suspicious behavior
- Protect against email bombing / SMS flooding
- Consider CAPTCHA after repeated failures
9) Best practices by channel
- Good for account recovery and low-friction login
- Magic links are convenient
- OTPs are better when users may access the app on a different device than their inbox
SMS
- Convenient but less secure than email
- Vulnerable to SIM swap and interception
- Use only if appropriate for your risk profile
Passkeys
If possible, consider passkeys/WebAuthn as a stronger modern passwordless option. Magic links and OTPs are simpler, but passkeys are more secure and phishing-resistant.
10) Common pitfalls
- Reusing tokens
- Storing plaintext codes
- Long expiry windows
- Not rate limiting
- Revealing whether an account exists
- Putting secrets in logs or analytics
- Using insecure redirects after verification
- Letting verification links work indefinitely
11) Minimal implementation outline
- User enters email/phone
- Generate random token/code
- Hash and store it with expiry
- Send link/code
- Verify token/code on return
- Mark it used
- Create authenticated session
- Redirect user
If you want, I can also give you:
- a Node.js/Express example
- a Next.js + Prisma example
- a Python/FastAPI example
- or a production-ready schema and API design