Prompt
How do I set up magic link login for a consumer app?
Latest observation
Setting up magic link login for a consumer app is mostly about getting three things right:
- Secure token generation and verification
- A smooth email delivery + landing flow
- Abuse prevention and session management
Here’s a practical blueprint.
1) Decide the login flow
A common magic-link flow looks like this:
- User enters their email.
- Your backend generates a single-use, short-lived token.
- You email a link like:
https://app.example.com/auth/magic?token=... - User clicks the link.
- Your app verifies the token.
- If valid, create a session and log the user in.
A safer version includes a code exchange:
- Link contains an opaque token or code.
- Frontend sends it to your backend.
- Backend verifies and issues a session cookie or JWT.
2) Use short-lived, single-use tokens
For consumer apps, treat magic links like password reset links:
- Expire quickly: 10–30 minutes is common.
- Single-use only: once redeemed, invalidate it.
- Random and unguessable: use 32+ bytes of cryptographic randomness.
- Store only a hash in your database, not the raw token.
Recommended token format
Use a random opaque token, not a user-identifying token in the URL.
Example:
- Generate
token = randomBytes(32) - Store
hash(token)in DB with:- user/email
- expiry time
- used_at = null
- created_at
- optionally IP / user agent metadata
When the user clicks the link:
- hash incoming token
- look up matching record
- check expiry and used status
- mark used
3) Add request throttling and anti-abuse controls
Magic links are easy to abuse if you don’t add guardrails.
At minimum:
- Rate limit by email address
- Rate limit by IP
- Add CAPTCHA after repeated requests
- Prevent email enumeration
Prevent enumeration
When someone enters an email, always respond with something like:
“If an account exists for that email, we sent a link.”
Do not reveal whether the email exists.
Add replay protection
- Invalidate previous outstanding tokens when issuing a new one, or
- Allow multiple but ensure only one can be used
4) Email delivery best practices
Magic link success depends heavily on deliverability.
Configure:
- SPF
- DKIM
- DMARC
Use:
- A reputable email provider (Postmark, SendGrid, SES, Mailgun, etc.)
- A recognizable sender name
- A clear subject line like:
Your sign-in link - Plain-text and HTML versions
Include:
- The link
- Expiration time
- A note like “If you didn’t request this, ignore this email.”
5) Make the link UX resilient
A good consumer-app magic link flow handles real-world behavior:
Mobile app considerations
If your app has mobile web or native apps:
- Use universal links / app links so the email opens the app when installed
- Fallback to web if the app isn’t installed
Browser considerations
- If the user clicks the link on a different device, don’t assume failure
- Let them log in on that device if the token is valid
Common implementation pattern
- User clicks email link
- Frontend route receives token
- Frontend POSTs token to backend
- Backend validates token and sets an HttpOnly secure session cookie
- Redirect to app home
6) Use secure session cookies after verification
After a valid magic link is redeemed, don’t keep the magic token around as the session credential.
Instead:
- Create a normal authenticated session
- Set a secure, HttpOnly cookie
- Use
SameSite=LaxorSameSite=Strictdepending on your app - Use
Securein production
Why?
Because magic links are one-time authentication proofs, not session tokens.
7) Protect against link leakage
Magic links can leak through:
- browser history
- server logs
- referrer headers
- email forwarding
Mitigations:
- Prefer a short opaque code that is exchanged server-side
- Avoid putting sensitive data in query strings beyond the random token
- Set
Referrer-Policy: no-referreror at leaststrict-origin - Use HTTPS only
- Keep tokens short-lived and one-time use
8) Consider device/session binding carefully
Sometimes teams want to bind the magic link to the device that requested it. This can reduce risk, but it can also hurt usability.
A practical compromise:
- Store the request IP and user agent for anomaly detection
- Don’t hard-bind unless you have a strong reason
- If a link is used from a very different context, you can step up auth or flag for review
For consumer apps, usability usually matters more than strict device binding.
9) Example backend flow
Request endpoint
POST /auth/magic/request
Input:
Backend:
- normalize email
- rate limit
- generate token
- store hash(token) with expiry
- email link
Return:
- generic success response
Verify endpoint
POST /auth/magic/verify
Input:
- token
Backend:
- hash token
- find matching unexpired unused record
- mark used
- create session
- return success / set cookie
10) Data model example
A simple table:
magic_login_tokens
- id
- user_id or email
- token_hash
- expires_at
- used_at
- created_at
- request_ip
- user_agent
If you haven’t created the user yet, you can attach it to email first and create/link user on first successful verification.
11) Security checklist
Before launch, make sure you have:
- HTTPS everywhere
- Random 256-bit tokens
- Tokens hashed in DB
- Single-use enforcement
- Short expiry
- Rate limiting
- Generic responses to prevent enumeration
- Secure session cookies
- Email provider with SPF/DKIM/DMARC
- Referrer policy set
- Logging and monitoring for abuse
- Account recovery plan if email access is lost
12) A note on MFA and account recovery
Magic links are convenient, but email access becomes the de facto authenticator.
For a consumer app, consider:
- optional TOTP or passkeys for stronger accounts
- backup codes for recovery
- support process for email changes
If your app handles sensitive data, magic link alone may not be enough.
13) Recommended “simple but solid” implementation
If you want a minimal robust setup:
- Email-only login
- 15-minute token expiration
- One-time opaque tokens
- Store token hash only
- POST token to backend for exchange
- HttpOnly session cookie
- Rate limit by IP/email
- Generic success message
- SPF/DKIM/DMARC configured
If you want, I can also give you:
- a database schema + API design,
- a Node/Express example,
- a Next.js implementation, or
- a mobile-friendly deep link flow.