How to confirm that a new user owns their address, what to allow before they do, how to handle resends and email changes, and a TypeScript example on Encore with Postgres, Pub/Sub and a cleanup cron job.

Email verification proves that the person who typed an address can receive mail there. Without it, typos leave accounts nobody can recover, and bots fill your user table with addresses that bounce and hurt your sender reputation.
The rules differ from magic link login: links can live for a day, users often get partial access first, and changing an address needs the same check. This guide covers them and builds the flow in TypeScript.
A verification token, an endpoint that consumes it, a resend path and a way to get rid of accounts that never verify. The token is random, stored as a hash and tied to both the user ID and the exact address being verified, which matters once users can change their email. A 24-hour expiry is common, since people sign up and check mail later, and the OWASP Authentication Cheat Sheet asks for generic responses on any endpoint that takes an address, so resend requests should not reveal whether an account exists either.
Blocking login until verification costs signups, because some people never come back to the email. A more forgiving pattern lets users in immediately and gates the actions where an unverified address causes harm: sending email to other people, inviting teammates, starting a subscription or connecting integrations. Store the state as a nullable email_verified_at timestamp rather than a boolean, so you can tell when it happened and reset it when the address changes.
Users lose verification emails to spam folders, so a resend button is needed, and it needs a cooldown (60 seconds is typical) plus a daily cap per account. Invalidate older tokens when you issue a new one so only the latest link works.
For an address change, keep the user's current email in place, store the new one on the verification token and send the link to the new address. Only when that link is used do you write the new address to the user row, which prevents someone with a hijacked session from quietly moving the account to their own inbox. Send a notice to the old address at the same time.
Store what the user typed and compare case-insensitively. RFC 5321 allows the local part of an address to be case-sensitive, but in practice almost no provider treats it that way, and two accounts for Ana@example.com and ana@example.com cause more support tickets than any mail server ever will. A unique index on lower(email) enforces this in Postgres.
Send from a domain with SPF, DKIM and DMARC records, keep the message short and plain, and do not let bots trigger sends to random addresses. Google's email sender guidelines list the authentication and complaint-rate requirements that bulk senders now have to meet, and unverified signup floods are one of the quickest ways to exceed them.
Encore is a backend framework with built-in infrastructure, and every piece of this flow, from the token table to the cleanup schedule, is declared in the service code below. Users and tokens live in an Encore Postgres database, emails go out through a Pub/Sub subscriber, and a cron job deletes accounts that stay unverified for a week. The cron job is managed by the Encore platform, and the database and topic are provisioned in your own AWS or GCP account.
Run in your terminal to get started locally.
-- accounts/migrations/1_create_accounts.up.sql
CREATE TABLE users (
id BIGSERIAL PRIMARY KEY,
email TEXT NOT NULL,
email_verified_at TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE UNIQUE INDEX users_email_lower ON users (lower(email));
CREATE TABLE email_verifications (
token_hash TEXT PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES users (id) ON DELETE CASCADE,
email TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
expires_at TIMESTAMPTZ NOT NULL,
used_at TIMESTAMPTZ
);
CREATE INDEX email_verifications_user ON email_verifications (user_id, created_at);
// accounts/encore.service.ts
import { Service } from "encore.dev/service";
export default new Service("accounts");
// accounts/verify.ts
import { api, APIError } from "encore.dev/api";
import { SQLDatabase } from "encore.dev/storage/sqldb";
import { Topic, Subscription } from "encore.dev/pubsub";
import { CronJob } from "encore.dev/cron";
import { secret } from "encore.dev/config";
import { createHash, randomBytes } from "node:crypto";
const db = new SQLDatabase("accounts", { migrations: "./migrations" });
const resendKey = secret("ResendAPIKey");
const sha256 = (s: string) => createHash("sha256").update(s).digest("hex");
interface VerificationEmail {
email: string;
token: string;
}
const verificationEmails = new Topic<VerificationEmail>("verification-emails", {
deliveryGuarantee: "at-least-once",
});
// Called by the signup endpoint, and by "change email" with the new address.
export const sendVerification = api(
{ expose: false },
async ({ userId, email }: { userId: number; email: string }): Promise<{ sent: boolean }> => {
const last = await db.queryRow<{ seconds: number; today: number }>`
SELECT coalesce(extract(epoch FROM now() - max(created_at)), 1e9)::int AS seconds,
count(*) FILTER (WHERE created_at > now() - interval '1 day')::int AS today
FROM email_verifications WHERE user_id = ${userId}`;
if (last && (last.seconds < 60 || last.today >= 5)) return { sent: false };
const token = randomBytes(32).toString("base64url");
await using tx = await db.begin();
await tx.exec`
UPDATE email_verifications SET used_at = now()
WHERE user_id = ${userId} AND used_at IS NULL`;
await tx.exec`
INSERT INTO email_verifications (token_hash, user_id, email, expires_at)
VALUES (${sha256(token)}, ${userId}, ${email}, now() + interval '24 hours')`;
await tx.commit();
await verificationEmails.publish({ email, token });
return { sent: true };
},
);
export const verifyEmail = api(
{ expose: true, method: "POST", path: "/accounts/verify-email" },
async ({ token }: { token: string }): Promise<{ userId: number; email: string }> => {
await using tx = await db.begin();
const claimed = await tx.queryRow<{ user_id: number; email: string }>`
UPDATE email_verifications SET used_at = now()
WHERE token_hash = ${sha256(token)} AND used_at IS NULL AND expires_at > now()
RETURNING user_id, email`;
if (!claimed) throw APIError.invalidArgument("verification link is invalid or expired");
try {
await tx.exec`
UPDATE users SET email = ${claimed.email}, email_verified_at = now()
WHERE id = ${claimed.user_id}`;
} catch {
throw APIError.alreadyExists("this address is already used by another account");
}
await tx.commit();
return { userId: claimed.user_id, email: claimed.email };
},
);
export const _sendVerificationEmail = new Subscription(verificationEmails, "send-verification-email", {
handler: async ({ email, 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 <hello@example.com>",
to: email,
subject: "Confirm your email address",
html: `<p><a href="https://app.example.com/verify#token=${token}">Confirm your address</a></p>`,
}),
});
if (!res.ok) throw new Error(`email provider returned ${res.status}`);
},
});
export const purgeUnverified = api({ expose: false }, async (): Promise<{ deleted: number }> => {
const row = await db.queryRow<{ n: number }>`
WITH gone AS (
DELETE FROM users
WHERE email_verified_at IS NULL AND created_at < now() - interval '7 days'
RETURNING id)
SELECT count(*)::int AS n FROM gone`;
return { deleted: row?.n ?? 0 };
});
const _purge = new CronJob("purge-unverified-users", {
title: "Delete accounts left unverified for 7 days",
schedule: "0 3 * * *",
endpoint: purgeUnverified,
});
The transaction uses await using, so it rolls back automatically if anything throws before commit(). The email change case is handled by the UPDATE users SET email line: when another account took the address in the meantime, the unique index on lower(email) rejects it and the caller gets a clear error instead of a duplicate account. Set the provider key with encore secret set --type dev,local ResendAPIKey and once more for production.
encore run starts Postgres locally and applies the migration, but the cron job does not run locally or in preview environments, so call purgeUnverified from the local development dashboard to test the cleanup. In deployed environments the schedule runs every night at 03:00 UTC, and each run shows up in a trace with the number of deleted accounts.
A coding agent can add a new gated action, such as "unverified users cannot create API keys", and the column it checks in the same change, then exercise both the blocked and the verified path against the local database.
Best fit: Apps that let users in at signup and want verification, resends and cleanup of abandoned accounts running against their own Postgres database.
After signup the backend stores a hash of a random token with the user ID and the address being verified, and emails a link containing the token. When the link is used, the backend claims the token, marks the address verified and enables whatever was gated on verification.
Yes, with limits. Letting users in immediately keeps signup conversion up, while gating actions that send email to others, invite teammates or spend money until the address is verified keeps abuse down.
Store the new address on the verification token instead of on the user, send the link to the new address and only update the user's email when that link is used. Notify the old address that a change was requested.
Keep users and hashed tokens in an Encore Postgres database, publish verification emails to a Pub/Sub topic and send them from a subscriber, and add an Encore cron job that deletes accounts left unverified for a week. The verify endpoint claims the token and sets email_verified_at in one transaction.
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.