What you'll build
- A waitlist form that works before JavaScript loads
- A Postgres table that stores emails and hashed confirmation tokens
- A double opt-in email with a link that expires
- A Redis rate limit per IP and per email address
- A "you're #123 in line" message and a live count on the landing page
Before you start
- Node.js 20.12 or newer
- A Next.js 16 app using the App Router
- A free CloudHike.dev account
What you'll build
A waitlist sounds simple: one input and a button. But a list full of typos, fake addresses and bot sign-ups is worth little on launch day. Double opt-in fixes that. People only count once they click a link in their inbox, so every address on the list is real and wants to hear from you.
- A visitor enters their email. A Server Action checks a Redis rate limit, saves the address with a hashed random token, and emails a confirmation link.
- They click the link and press Confirm my spot. The row is marked confirmed and the token is cleared.
- The page shows their place in line, and the landing page shows how many people have joined.
Step 1: Deploy the services and install packages
- Sign in at cloudhike.dev and create a project.
- Deploy Postgres, Redis and Email. Email asks you to accept the email policy first.
- Click Copy as .env, paste the values into
.env.local, and add your app's address.
DATABASE_URL=postgresql://...
DIRECT_URL=postgresql://...
REDIS_URL=redis://...
EMAIL_API_URL=https://...
EMAIL_API_KEY=...
APP_URL=http://localhost:3000npm install drizzle-orm pg ioredis server-only
npm install -D drizzle-kit @types/pgStep 2: Create the waitlist table
One table is enough. The id grows with each sign-up, which gives you a fair order for free. The token is stored as a SHA-256 hash, so a leaked database can't be used to confirm anyone.
import { pgTable, serial, text, timestamp, uniqueIndex } from "drizzle-orm/pg-core";
export const waitlist = pgTable(
"waitlist",
{
id: serial("id").primaryKey(),
email: text("email").notNull().unique(),
tokenHash: text("token_hash"),
tokenExpiresAt: timestamp("token_expires_at", { withTimezone: true }),
confirmedAt: timestamp("confirmed_at", { withTimezone: true }),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
},
(t) => [uniqueIndex("waitlist_token_hash_idx").on(t.tokenHash)],
);import "server-only";
import { drizzle } from "drizzle-orm/node-postgres";
import { Pool } from "pg";
// One small pool per process, kept across dev hot reloads.
const globalForDb = globalThis as unknown as { pool?: Pool };
const pool = globalForDb.pool ?? new Pool({ connectionString: process.env.DATABASE_URL, max: 5 });
if (process.env.NODE_ENV !== "production") globalForDb.pool = pool;
export const db = drizzle(pool);Migrations should use DIRECT_URL, which skips the connection pooler. See Connect for why.
import { defineConfig } from "drizzle-kit";
try {
process.loadEnvFile(".env.local");
} catch {
// On CI the variables are already set.
}
export default defineConfig({
dialect: "postgresql",
schema: "./db/schema.ts",
out: "./drizzle",
dbCredentials: { url: process.env.DIRECT_URL ?? process.env.DATABASE_URL! },
});npx drizzle-kit pushOpen the project's database explorer in the CloudHike dashboard and you'll see the empty waitlist table on the Data tab.
Step 3: Add a Redis rate limit
Every sign-up sends an email, so a bot hammering the form costs you email allowance and sender reputation. Limit each IP address, and each email address, to a few tries in a window.
import "server-only";
import Redis from "ioredis";
const globalForRedis = globalThis as unknown as { redis?: Redis };
export const redis = globalForRedis.redis ?? new Redis(process.env.REDIS_URL!, { maxRetriesPerRequest: 2 });
if (process.env.NODE_ENV !== "production") globalForRedis.redis = redis;import "server-only";
import { redis } from "@/lib/redis";
// Fixed window: at most `limit` calls per `windowSec` for each key.
export async function allow(key: string, limit: number, windowSec: number) {
try {
const k = `rate:${key}`;
const count = await redis.incr(k);
if (count === 1) await redis.expire(k, windowSec);
return count <= limit;
} catch (err) {
// If Redis is unreachable, let the request through rather than break sign-ups.
console.error("rate limit", err);
return true;
}
}For a sliding window and more patterns, see Rate Limit Next.js with Redis.
Step 4: Build the form and the Server Action
First, a small server-only email helper. It's the same one built in How to Send Email from Next.js:
import "server-only";
export class EmailError extends Error {
constructor(message: string, public status: number, public retryAfter?: number) {
super(message);
}
}
export async function sendEmail(email: { to: string; subject: string; html: string; text: string; replyTo?: string }) {
const res = await fetch(`${process.env.EMAIL_API_URL}/send`, {
method: "POST",
headers: { "content-type": "application/json", "x-api-key": process.env.EMAIL_API_KEY! },
body: JSON.stringify(email),
});
if (!res.ok) {
const retryAfter = Number(res.headers.get("retry-after")) || undefined;
const { message } = await res.json().catch(() => ({ message: res.statusText }));
throw new EmailError(message ?? "Email failed", res.status, retryAfter);
}
}The action does the real work. It answers the same way whether the email is new, waiting for confirmation or already confirmed, so nobody can use the form to check who has joined.
"use server";
import { createHash, randomBytes } from "node:crypto";
import { and, count, eq, gt, isNotNull, isNull, lte } from "drizzle-orm";
import { headers } from "next/headers";
import { waitlist } from "@/db/schema";
import { db } from "@/lib/db";
import { EmailError, sendEmail } from "@/lib/email";
import { allow } from "@/lib/rate-limit";
import { redis } from "@/lib/redis";
export type JoinState = { ok: boolean; message: string } | null;
export type ConfirmState = { ok: true; position: number } | { ok: false; message: string } | null;
const hash = (token: string) => createHash("sha256").update(token).digest("hex");
const TOKEN_TTL_MS = 24 * 60 * 60 * 1000;
async function clientIp() {
const h = await headers();
return h.get("x-forwarded-for")?.split(",")[0]?.trim() || h.get("x-real-ip") || "unknown";
}
export async function joinWaitlist(_prev: JoinState, form: FormData): Promise<JoinState> {
// Honeypot: people never see this field, simple bots fill it in.
if (form.get("company")) return { ok: true, message: "Check your inbox to confirm your spot." };
const email = String(form.get("email") ?? "").trim().toLowerCase();
if (!/^\S+@\S+\.\S+$/.test(email) || email.length > 254) {
return { ok: false, message: "Please enter a valid email address." };
}
const ip = await clientIp();
if (!(await allow(`waitlist:ip:${ip}`, 5, 600)) || !(await allow(`waitlist:email:${email}`, 3, 3600))) {
return { ok: false, message: "Too many tries. Please wait a few minutes and try again." };
}
const token = randomBytes(32).toString("base64url");
const tokenHash = hash(token);
const tokenExpiresAt = new Date(Date.now() + TOKEN_TTL_MS);
// New email: insert. Unconfirmed: issue a fresh token. Confirmed: leave it alone.
const [row] = await db
.insert(waitlist)
.values({ email, tokenHash, tokenExpiresAt })
.onConflictDoUpdate({
target: waitlist.email,
set: { tokenHash, tokenExpiresAt },
setWhere: isNull(waitlist.confirmedAt),
})
.returning({ id: waitlist.id });
if (row) {
const link = `${process.env.APP_URL}/waitlist/confirm?token=${token}`;
try {
await sendEmail({
to: email,
subject: "Confirm your spot on the waitlist",
text: `Thanks for joining! Confirm your spot here (the link works for 24 hours):\n\n${link}\n\nIf you didn't sign up, ignore this email.`,
html: `<p>Thanks for joining!</p><p><a href="${link}">Confirm my spot</a></p><p>The link works for 24 hours. If you didn't sign up, ignore this email.</p>`,
replyTo: "hello@example.com",
});
} catch (err) {
if (err instanceof EmailError && err.status === 429) {
return { ok: false, message: "We're getting a lot of sign-ups right now. Please try again in a minute." };
}
console.error("waitlist confirmation email", err);
return { ok: false, message: "We couldn't send the confirmation email. Please try again." };
}
}
return { ok: true, message: "Check your inbox to confirm your spot." };
}
export async function confirmSpot(_prev: ConfirmState, form: FormData): Promise<ConfirmState> {
const token = String(form.get("token") ?? "");
if (!token) return { ok: false, message: "This link is incomplete." };
const [row] = await db
.update(waitlist)
.set({ confirmedAt: new Date(), tokenHash: null, tokenExpiresAt: null })
.where(and(eq(waitlist.tokenHash, hash(token)), isNull(waitlist.confirmedAt), gt(waitlist.tokenExpiresAt, new Date())))
.returning({ id: waitlist.id });
if (!row) {
return { ok: false, message: "This link has expired or was already used. Join again to get a new one." };
}
// Your place: confirmed people who signed up before you, plus you.
const [{ position }] = await db
.select({ position: count() })
.from(waitlist)
.where(and(isNotNull(waitlist.confirmedAt), lte(waitlist.id, row.id)));
await redis.del("waitlist:count").catch(() => {});
return { ok: true, position };
}x-forwarded-for can be faked unless your host sets it. Vercel and most platforms overwrite it with the real client IP. If you run behind your own proxy, make sure it does the same.
"use client";
import { useActionState } from "react";
import { joinWaitlist } from "./waitlist/actions";
export function WaitlistForm() {
const [state, action, pending] = useActionState(joinWaitlist, null);
if (state?.ok) return <p role="status">{state.message}</p>;
return (
<form action={action} className="flex flex-col gap-2 sm:flex-row">
<input name="email" type="email" autoComplete="email" placeholder="you@example.com" required className="flex-1" />
{/* Honeypot: hidden from people and screen readers */}
<input name="company" tabIndex={-1} autoComplete="off" aria-hidden="true" className="hidden" />
<button disabled={pending}>{pending ? "Joining…" : "Join the waitlist"}</button>
{state && !state.ok && <p role="alert" style={{ color: "crimson" }}>{state.message}</p>}
</form>
);
}Step 5: Confirm the email and show their place in line
The link opens a page with a button, and only the button confirms. That's on purpose: many company mail filters open every link in an email to scan it. If a plain visit confirmed the spot, those scanners would confirm addresses nobody checked.
import type { Metadata } from "next";
import { ConfirmForm } from "./confirm-form";
export const metadata: Metadata = { title: "Confirm your spot", referrer: "no-referrer" };
export default async function ConfirmPage({ searchParams }: { searchParams: Promise<{ token?: string | string[] }> }) {
const { token } = await searchParams;
const value = Array.isArray(token) ? token[0] : token;
return (
<main className="mx-auto max-w-md p-8">
{value ? <ConfirmForm token={value} /> : <p>This link is incomplete. Please use the link from your email.</p>}
</main>
);
}"use client";
import Link from "next/link";
import { useActionState } from "react";
import { confirmSpot } from "../actions";
export function ConfirmForm({ token }: { token: string }) {
const [state, action, pending] = useActionState(confirmSpot, null);
if (state?.ok) {
return (
<div role="status">
<h1 className="text-3xl font-bold">You're #{state.position.toLocaleString("en-US")} in line</h1>
<p>We'll email you when it's your turn.</p>
</div>
);
}
return (
<form action={action} className="grid gap-3">
<h1 className="text-2xl font-bold">One last step</h1>
<input type="hidden" name="token" value={token} />
<button disabled={pending}>{pending ? "Confirming…" : "Confirm my spot"}</button>
{state && !state.ok && (
<p role="alert">
{state.message} <Link href="/">Back to the waitlist</Link>
</p>
)}
</form>
);
}The place in line counts only confirmed people, ordered by when they signed up. Someone who joined earlier but confirms later moves in ahead of later sign-ups. That keeps it fair to early birds who were slow to check their inbox.
Step 6: Show the count on the landing page
"Join 1,240 others" is good social proof. Counting rows on every page view is wasteful, so cache the number in Redis for a minute. The confirm action deletes the key, so a new confirmation shows up right away.
import "server-only";
import { count, isNotNull } from "drizzle-orm";
import { waitlist } from "@/db/schema";
import { db } from "@/lib/db";
import { redis } from "@/lib/redis";
export async function confirmedCount() {
const cached = await redis.get("waitlist:count").catch(() => null);
if (cached !== null) return Number(cached);
const [{ n }] = await db.select({ n: count() }).from(waitlist).where(isNotNull(waitlist.confirmedAt));
await redis.set("waitlist:count", n, "EX", 60).catch(() => {});
return n;
}import { connection } from "next/server";
import { confirmedCount } from "@/lib/waitlist-count";
import { WaitlistForm } from "./waitlist-form";
export default async function Home() {
await connection(); // render per request, not once at build time
const joined = await confirmedCount();
return (
<main className="mx-auto grid max-w-xl gap-6 p-8 text-center">
<h1 className="text-4xl font-bold">Something new is coming</h1>
<p>Be the first to know when we launch.</p>
<WaitlistForm />
{joined > 0 && <p className="text-sm text-gray-500">Join {joined.toLocaleString("en-US")} others on the waitlist.</p>}
</main>
);
}If your app turns on cacheComponents, wrap the count in a <Suspense> boundary so the rest of the page can still be prerendered.
Try it: run npm run dev, join with your own email, click the link and confirm. The count on the home page goes up by one.
Production checklist
- Add every variable from
.env.localto your host, and setAPP_URLto your real address so links in emails work. - Send from your own verified domain and set a reply-to address you read.
- Run
npx drizzle-kit push(or your migrations) against production before the first deploy. - Clean up old unconfirmed rows now and then:
DELETE FROM waitlist WHERE confirmed_at IS NULL AND created_at < now() - interval '7 days';. - Export the confirmed list when you launch:
psql "$DIRECT_URL" -c "\copy (SELECT email, confirmed_at FROM waitlist WHERE confirmed_at IS NOT NULL ORDER BY id) TO 'waitlist.csv' CSV HEADER". - Watch the bounce rate on the Email overview. A spike usually means a bot found the form, so tighten the rate limit.
- Your launch announcement is a one-time bulk send, which isn't transactional mail. Check the email policy and use a newsletter tool for it.
- Check the pricing page for what Postgres, Redis and Email cost as the list grows.
Frequently asked questions
What is double opt-in for a waitlist?
Double opt-in means a sign-up only counts after the person clicks a confirmation link sent to their email. It keeps typos, fake addresses and bot sign-ups off your list, and proves the person wanted to join.
How do I create a confirmation link in Next.js?
Generate a random token with crypto.randomBytes, store a hash of it with an expiry next to the email, and email a link that contains the token. When the link is used, hash the token again and look up the matching row.
Why does the confirmation link need a button?
Many corporate email filters visit every link in a message to scan it for threats. If simply opening the link confirmed the address, those scanners would confirm it too. A button that submits a form is only pressed by a person.
How do I rate limit a Server Action in Next.js?
Read the client IP from the x-forwarded-for header with await headers(), then count requests per IP in Redis with INCR and an expiry. Refuse the action when the count passes your limit for the window.
Can I email everyone on the waitlist when I launch?
A one-time announcement to your whole list is bulk mail, not transactional email, so it doesn't belong on a transactional sender like CloudHike Email. Export the confirmed list and send the announcement with a newsletter tool.
