Skip to content

User signup flow

Send welcome and verification emails during user signup with secure token-based email verification.

This example demonstrates a complete user registration system with welcome emails and email verification.

Configure the email binding and KV namespaces in your Wrangler configuration file:

{
	"send_email": [{ "name": "EMAIL" }],
	"kv_namespaces": [
		{ "binding": "USERS", "id": "<USERS_KV_NAMESPACE_ID>" },
		{
			"binding": "VERIFICATION_TOKENS",
			"id": "<VERIFICATION_TOKENS_KV_NAMESPACE_ID>",
		},
	],
	"vars": {
		"DOMAIN": "yourdomain.com",
		"COMPANY_NAME": "Acme Inc.",
	},
}
[[send_email]]
name = "EMAIL"

[[kv_namespaces]]
binding = "USERS"
id = "<USERS_KV_NAMESPACE_ID>"

[[kv_namespaces]]
binding = "VERIFICATION_TOKENS"
id = "<VERIFICATION_TOKENS_KV_NAMESPACE_ID>"

[vars]
DOMAIN = "yourdomain.com"
COMPANY_NAME = "Acme Inc."

The Worker exposes two routes. POST /signup stores a pending user in KV and sends a combined welcome and verification email with a tokenized link. If sending fails, the user remains unverified and can retry POST /signup to receive a new token. GET /verify validates the current token and marks the user as verified.

interface Env {
	EMAIL: SendEmail;
	USERS: KVNamespace;
	VERIFICATION_TOKENS: KVNamespace;
	DOMAIN: string;
	COMPANY_NAME: string;
}

interface User {
	id: string;
	email: string;
	firstName: string;
	verified: boolean;
	verificationToken?: string;
	createdAt: string;
}

export default {
	async fetch(request: Request, env: Env): Promise<Response> {
		const url = new URL(request.url);

		if (url.pathname === "/signup" && request.method === "POST") {
			return handleSignup(request, env);
		}

		if (url.pathname === "/verify" && request.method === "GET") {
			return handleVerification(request, env);
		}

		return new Response("Not Found", { status: 404 });
	},
};

async function handleSignup(request: Request, env: Env): Promise<Response> {
	const { email, firstName } = await request.json();

	// Validate input
	if (!email || !firstName || !isValidEmail(email)) {
		return new Response(JSON.stringify({ error: "Invalid input" }), {
			status: 400,
		});
	}

	// Reject duplicate signups only after the user has verified their address
	const existingData = await env.USERS.get(email);
	const existingUser: User | null = existingData
		? JSON.parse(existingData)
		: null;

	if (existingUser?.verified) {
		return new Response(JSON.stringify({ error: "User already exists" }), {
			status: 409,
		});
	}

	// Issue a new verification token (expires in 1 hour) and invalidate any previous one
	const verificationToken = crypto.randomUUID();
	if (existingUser?.verificationToken) {
		await env.VERIFICATION_TOKENS.delete(existingUser.verificationToken);
	}

	const user: User = existingUser
		? {
				...existingUser,
				firstName,
				verificationToken,
			}
		: {
				id: crypto.randomUUID(),
				email,
				firstName,
				verified: false,
				verificationToken,
				createdAt: new Date().toISOString(),
			};

	await env.USERS.put(email, JSON.stringify(user));
	await env.VERIFICATION_TOKENS.put(verificationToken, email, {
		expirationTtl: 3600,
	});

	// Send one combined welcome and verification email so a send error leaves a clean retry path
	const verificationUrl = `https://${env.DOMAIN}/verify?token=${verificationToken}`;
	try {
		await env.EMAIL.send({
			to: email,
			from: `noreply@${env.DOMAIN}`,
			subject: `Welcome to ${env.COMPANY_NAME} — verify your email`,
			html: `
      <h1>Welcome ${firstName}!</h1>
      <p>Thanks for joining ${env.COMPANY_NAME}. Select the link below to verify your email address:</p>
      <a href="${verificationUrl}" style="background: #007bff; color: white; padding: 12px 24px; text-decoration: none; border-radius: 4px;">Verify Email</a>
      <p>This link expires in 1 hour.</p>
    `,
		});
	} catch (error) {
		console.error("Failed to send verification email", error);
		return new Response(
			JSON.stringify({
				error:
					"Could not send verification email. Retry signup to request a new link.",
			}),
			{ status: 503 },
		);
	}

	return new Response(
		JSON.stringify({
			success: true,
			message: existingUser
				? "Verification email resent. Check your email."
				: "Account created. Check your email.",
			userId: user.id,
		}),
		{ status: existingUser ? 200 : 201 },
	);
}

async function handleVerification(
	request: Request,
	env: Env,
): Promise<Response> {
	const url = new URL(request.url);
	const token = url.searchParams.get("token");

	if (!token) {
		return new Response("Missing token", { status: 400 });
	}

	// Verify token
	const userEmail = await env.VERIFICATION_TOKENS.get(token);
	if (!userEmail) {
		return new Response("Invalid or expired token", { status: 400 });
	}

	// Get and update user
	const userData = await env.USERS.get(userEmail);
	if (!userData) {
		return new Response("User not found", { status: 404 });
	}

	const user: User = JSON.parse(userData);
	if (user.verified || user.verificationToken !== token) {
		return new Response("Invalid or expired token", { status: 400 });
	}

	user.verified = true;
	delete user.verificationToken;

	await env.USERS.put(user.email, JSON.stringify(user));
	await env.VERIFICATION_TOKENS.delete(token);

	return new Response(
		`
    <html>
      <body style="font-family: Arial, sans-serif; text-align: center; padding: 50px;">
        <h1>Email Verified!</h1>
        <p>Welcome ${user.firstName}! Your account is now active.</p>
        <a href="/" style="background: #28a745; color: white; padding: 12px 24px; text-decoration: none; border-radius: 4px;">Continue</a>
      </body>
    </html>
  `,
		{
			headers: { "Content-Type": "text/html" },
		},
	);
}

function isValidEmail(email: string): boolean {
	return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}

Next steps

Was this helpful?