Prompt
How do I implement passwordless login with magic links?
Latest observation
Oct 31, 2026
OpenAI APIWeb search: off
Passwordless login with magic links usually works like this:
- User enters their email address.
- You generate a short-lived, single-use token.
- You email a link containing that token.
- When the user clicks the link, your backend validates the token and logs them in.
- You create a session (cookie/JWT) and invalidate the token.
Core flow
1) Request magic link
- User submits email to
/auth/magic-link/request - Verify the email exists or always return a generic success message to avoid account enumeration
- Generate a cryptographically secure random token
- Store a hashed version of the token server-side with:
- user ID / email
- expiry timestamp
- one-time-use flag
- optional IP / user-agent metadata
- Email a link like:
https://yourapp.com/auth/magic-link/verify?token=...
2) Verify magic link
- User clicks the link
- Backend receives token at
/auth/magic-link/verify - Hash the provided token and look it up
- Check:
- exists
- not expired
- not already used
- Mark token as used
- Create authenticated session
- Redirect user to app
Security best practices
Use short expiry
- 10–30 minutes is common
Make tokens single-use
- Prevent replay attacks
Store only a hashed token
- If your DB leaks, raw tokens aren’t exposed
Rate limit requests
- Limit per email, IP, and device
- Prevent abuse and email flooding
Avoid account enumeration
- Always respond with something like:
- “If that email exists, we sent a link.”
Bind to optional context carefully
- You can log IP/user-agent and warn on mismatch
- Don’t over-restrict or legitimate users will fail if their IP changes
Use HTTPS
- Magic links must only be sent and opened over HTTPS
Prefer session cookies over JWT in many web apps
- Especially for browser-based apps, secure HTTP-only cookies are usually simpler and safer
Invalidate old tokens
- If a new magic link is issued, you may want to revoke previous pending tokens
Simple data model
CREATE TABLE magic_links (
id UUID PRIMARY KEY,
user_id UUID NOT NULL,
token_hash TEXT NOT NULL,
expires_at TIMESTAMP NOT NULL,
used_at TIMESTAMP NULL,
created_at TIMESTAMP NOT NULL DEFAULT NOW()
);
Example implementation outline
Generate token
import crypto from "crypto";
function generateMagicToken() {
return crypto.randomBytes(32).toString("hex");
}
Hash token before storing
function hashToken(token) {
return crypto.createHash("sha256").update(token).digest("hex");
}
Request endpoint
app.post("/auth/magic-link/request", async (req, res) => {
const { email } = req.body;
// Always respond generically
const user = await db.users.findByEmail(email);
if (user) {
const token = generateMagicToken();
const tokenHash = hashToken(token);
await db.magic_links.insert({
user_id: user.id,
token_hash: tokenHash,
expires_at: new Date(Date.now() + 15 * 60 * 1000),
});
const link = `https://yourapp.com/auth/magic-link/verify?token=${token}`;
await sendEmail(email, "Your login link", `Click here: ${link}`);
}
res.json({ message: "If that email exists, we sent a link." });
});
Verify endpoint
app.get("/auth/magic-link/verify", async (req, res) => {
const { token } = req.query;
const tokenHash = hashToken(token);
const record = await db.magic_links.findOne({
token_hash: tokenHash,
used_at: null,
expires_at_gt: new Date(),
});
if (!record) {
return res.status(400).send("Invalid or expired link");
}
await db.magic_links.markUsed(record.id);
const session = await createSession(record.user_id);
res.cookie("session", session, {
httpOnly: true,
secure: true,
sameSite: "lax",
});
res.redirect("/dashboard");
});
UX tips
- Tell users to check spam/junk
- Allow “resend link”
- Make the email subject clear: “Your sign-in link”
- Add a fallback code in case email client breaks the link
Common pitfalls
- Putting the token in logs or analytics
- Using long-lived tokens
- Reusing tokens
- Not rate limiting
- Not hashing stored tokens
- Redirecting to arbitrary URLs without validation
Recommended production pattern
If you want the safest practical setup:
- One-time, 15-minute token
- Hashed token storage
- Generic response for requests
- Secure, HTTP-only session cookie after verification
- Rate limiting + CAPTCHA after repeated failures
- Email deliverability setup: SPF, DKIM, DMARC
If you want, I can also provide:
- a Node/Express, Python/FastAPI, or Next.js implementation, or
- a version using JWT-based magic links vs database-stored tokens.
Brands