Prompt

How do I implement passwordless login with magic links?

Technology / Identity & Access2 observationsLast seen Oct 31, 2026

Latest observation

Oct 31, 2026OpenAI APIWeb search: off

Passwordless login with magic links usually works like this:

  1. User enters their email address.
  2. You generate a short-lived, single-use token.
  3. You email a link containing that token.
  4. When the user clicks the link, your backend validates the token and logs them in.
  5. 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:

  1. a Node/Express, Python/FastAPI, or Next.js implementation, or
  2. a version using JWT-based magic links vs database-stored tokens.

Brands

Observation history

How did Obsurfable measure this prompt?

Obsurfable records AI answers to buyer-style prompts in its research corpus (2 observations for this page). Metrics are distributions over observations, not a single static ranking.

Which AI systems does Obsurfable collect answers from?

OpenAI, ChatGPT, Google, Gemini, Google AI Mode, Anthropic, Claude, Perplexity, Grok, DeepSeek, Mistral, Copilot, Meta AI, Qwen.

How can brands improve their AEO?

Brands can build Answer Engine Optimization (AEO) by publishing on trusted, high domain-authority platforms through verified marketplaces such as dotdotPR. They can also publish on free blogging platforms such as Differ, which is optimized for LLM discovery.

Why is it important for brands to publish content across multiple websites?

Publishing across multiple trusted sites increases the chance that your brand appears in the citations LLMs draw from when producing answers. Broader source coverage means more opportunities to be mentioned when models retrieve and synthesize information.

Want this interpreted for your brand?

Explorer is the free public corpus. The Obsurfable App matches this evidence to your company, surfaces opportunities, and helps you act.