How to issue single-use sign-in links, store only a hash of each token, survive email link scanners and turn a verified link into a session, with a TypeScript example on Encore.

Magic links replace the password with a link sent to the user's inbox. The client side is one email field and a button, while the backend has to issue tokens nobody can guess, store only hashes and make each link work once.
After launch, corporate mail scanners start opening links before users do. This guide covers the token design, a confirm step that survives scanners and a working TypeScript service.
The user submits an email address, and the backend creates a random token, stores a hash of it with an expiry and sends a link containing the raw token. When the link comes back, the backend hashes the token it receives, finds the matching unexpired and unused row, marks it used and creates a session for the user behind that address. If no account exists yet, the same step creates one, which is why magic links double as signup.
The request endpoint returns the same response whether or not the address belongs to an account. A response that differs tells an attacker which addresses are registered, and the OWASP Authentication Cheat Sheet recommends generic responses for exactly this reason.
Generate at least 32 bytes from a cryptographically secure source such as Node's crypto.randomBytes and encode them as base64url so they fit in a URL. Store a SHA-256 hash of the token rather than the token itself, so a leaked backup or a read replica in the wrong hands holds nothing that can sign anyone in. A fast hash is fine here, since the input is 256 random bits and cannot be brute-forced the way a human password can.
Keep the expiry short, 10 to 15 minutes, and mark the token used in the same statement that checks it. An UPDATE ... WHERE used_at IS NULL AND expires_at > now() RETURNING either claims the row or returns nothing, so two clicks racing each other cannot both create a session.
Security gateways such as Microsoft Defender Safe Links rewrite and open links in incoming mail to check where they lead. If your backend consumes the token on the GET request for the link, the scanner signs in, the token is spent and the actual user sees an error a few seconds later.
The fix is to make opening the link harmless. Send the user to a confirm page with the token in the URL fragment (/login/confirm#token=...), which browsers never send to the server, as described in RFC 3986. The page reads the fragment with JavaScript and sends it in a POST, either automatically or behind a "Sign in" button, and scanners that only fetch the page never reach the token.
Anyone can type someone else's address into the form, so cap requests per address (for example five per 15 minutes) and per IP at the edge, and return the generic response when the cap is hit. Never put the email address in the link, since the token alone identifies the request. When a new link is issued, older unused links for that address can stay valid until they expire or be invalidated, and invalidating them is the safer default for apps that hold sensitive data.
Encore is a backend framework with built-in infrastructure, and the token table, the email queue and the provider key in this flow are all declared next to the endpoints that use them. The Postgres database holds hashed tokens, users and sessions, a Pub/Sub topic takes email sending off the request path, and the provider key is an Encore secret. When you deploy, Encore provisions the database and topic in your own AWS or GCP account. Encore provisions an IAM role for the service, or a service account on GCP.
Run in your terminal to get started locally.
-- auth/migrations/1_create_auth.up.sql
CREATE TABLE users (
id BIGSERIAL PRIMARY KEY,
email TEXT NOT NULL UNIQUE,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
last_login_at TIMESTAMPTZ
);
CREATE TABLE login_tokens (
token_hash TEXT PRIMARY KEY,
email TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
expires_at TIMESTAMPTZ NOT NULL,
used_at TIMESTAMPTZ
);
CREATE INDEX login_tokens_email_created ON login_tokens (email, created_at);
CREATE TABLE sessions (
token_hash TEXT PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES users (id),
expires_at TIMESTAMPTZ NOT NULL
);
// auth/encore.service.ts
import { Service } from "encore.dev/service";
export default new Service("auth");
// auth/magiclink.ts
import { api, APIError } from "encore.dev/api";
import { SQLDatabase } from "encore.dev/storage/sqldb";
import { Topic, Subscription } from "encore.dev/pubsub";
import { secret } from "encore.dev/config";
import { IsEmail } from "encore.dev/validate";
import { createHash, randomBytes } from "node:crypto";
const db = new SQLDatabase("auth", { migrations: "./migrations" });
const resendKey = secret("ResendAPIKey");
const APP_URL = "https://app.example.com";
const sha256 = (s: string) => createHash("sha256").update(s).digest("hex");
interface LoginEmail {
email: string;
token: string;
}
const loginEmails = new Topic<LoginEmail>("login-emails", {
deliveryGuarantee: "at-least-once",
});
export const requestLink = api(
{ expose: true, method: "POST", path: "/auth/magic-link" },
async ({ email }: { email: string & IsEmail }): Promise<void> => {
const address = email.trim().toLowerCase();
await using tx = await db.begin();
// One request per address at a time, so concurrent requests cannot all pass the cap.
await tx.exec`SELECT pg_advisory_xact_lock(hashtext(${address}))`;
const recent = await tx.queryRow<{ n: number }>`
SELECT count(*)::int AS n FROM login_tokens
WHERE email = ${address} AND created_at > now() - interval '15 minutes'`;
if ((recent?.n ?? 0) >= 5) return; // same response as success
const token = randomBytes(32).toString("base64url");
await tx.exec`
INSERT INTO login_tokens (token_hash, email, expires_at)
VALUES (${sha256(token)}, ${address}, now() + interval '15 minutes')`;
await tx.commit();
await loginEmails.publish({ email: address, token });
},
);
export const verifyLink = api(
{ expose: true, method: "POST", path: "/auth/magic-link/verify" },
async ({ token }: { token: string }): Promise<{ sessionToken: string; userId: number }> => {
// One transaction, so a failure before the session exists leaves the link unused.
await using tx = await db.begin();
const claimed = await tx.queryRow<{ email: string }>`
UPDATE login_tokens SET used_at = now()
WHERE token_hash = ${sha256(token)}
AND used_at IS NULL AND expires_at > now()
RETURNING email`;
if (!claimed) throw APIError.unauthenticated("link is invalid or expired");
const user = await tx.queryRow<{ id: number }>`
INSERT INTO users (email) VALUES (${claimed.email})
ON CONFLICT (email) DO UPDATE SET last_login_at = now()
RETURNING id`;
const sessionToken = randomBytes(32).toString("base64url");
await tx.exec`
INSERT INTO sessions (token_hash, user_id, expires_at)
VALUES (${sha256(sessionToken)}, ${user!.id}, now() + interval '30 days')`;
await tx.commit();
return { sessionToken, userId: user!.id };
},
);
export const _sendLoginEmail = new Subscription(loginEmails, "send-login-email", {
handler: async ({ email, token }) => {
const link = `${APP_URL}/login/confirm#token=${token}`;
const res = await fetch("https://api.resend.com/emails", {
method: "POST",
headers: {
Authorization: `Bearer ${resendKey()}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
from: "Example <login@example.com>",
to: email,
subject: "Your sign-in link",
html: `<p><a href="${link}">Sign in</a>. The link expires in 15 minutes.</p>`,
}),
});
if (!res.ok) throw new Error(`email provider returned ${res.status}`);
},
retryPolicy: { minBackoff: "10s", maxRetries: 5 },
});
Set the provider key once per environment with encore secret set --type dev,local ResendAPIKey and encore secret set --type prod ResendAPIKey, and encore run starts Postgres locally and runs the migration. The subscriber throws on a non-2xx response so Pub/Sub retries the send, and since delivery is at least once a user can occasionally receive the same link twice, which is harmless as both carry the same token. The raw token sits in the queue message for the few seconds before the email goes out, and the 15-minute expiry bounds that exposure.
Every request, publish and email call shows up in one trace, which shows quickly whether a missing email failed at the provider or never left the queue. An agent asked to add "sign in with a link" can create the table, the topic and the secret reference in the same change as the endpoints and run the whole flow locally before anyone touches a cloud console.
Best fit: Apps that want passwordless sign-in with tokens, users and sessions in their own Postgres database and email delivery that retries on its own.
The user enters an email address, the backend stores a hash of a random single-use token with an expiry and emails a link that carries the token. When the user opens the link, the backend checks the hash, marks the token used and creates a session, so possession of the inbox replaces the password.
Yes, when the token is long and random, stored only as a hash, valid for minutes rather than days and usable once. The remaining risk sits in the email account itself, so treat a magic link like a password reset link and rate limit requests per address.
Email security scanners open links to check them, and a backend that consumes the token on a GET request treats that scan as a login. Put the token in the URL fragment and consume it only from a POST that the confirm page sends.
Store hashed tokens in an Encore Postgres database, publish a message to a Pub/Sub topic from the request endpoint, and send the email from a subscriber that reads the provider key from an Encore secret. A verify endpoint marks the token used with one UPDATE and creates the session.
Deploy to your cloud on AWS and Google Cloud
without managing infrastructure
Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.