How to Add WhatsApp OTP Login to a Next.js App (App Router, with Fallback and Secure Sessions)

2026-12-03来源 dev.toEnglish

Phone-number login is popular in markets where users live on WhatsApp, and in apps where email signup creates friction. In this tutorial we'll build WhatsApp OTP login in Next.js (App Router) with Route Handlers, a Telegram fallback, and a secure cookie-based session.

We'll use the Authly OTP API and its Node.js SDK. I'm the maker of Authly, but the structure works with any OTP provider.

What we're building

  • POST /api/otp/send sends a code to a phone number
  • POST /api/otp/verify checks the code and creates a session
  • A login form (client component)
  • Middleware that protects pages for logged-in users only

One design choice matters for security: the browser never tells the server which phone number or OTP id to verify. After sending a code, the server stores them in a short-lived, signed, httpOnly cookie. At verification time, the client sends only the code. This stops a user from verifying one number and claiming another.

Setup

npx create-next-app@latest otp-login cd otp-login npm install authly-otp jose 

Create .env.local:

AUTHLY_API_KEY=your_api_key SESSION_SECRET=generate_with_openssl_rand_-base64_32 

Generate the secret with openssl rand -base64 32. New Authly accounts get a free test quota (7 WhatsApp, 7 Telegram and 100 Email OTPs), enough to try this end to end. Keep both values on the server only, never in NEXT_PUBLIC_ variables.

A small helper for signed tokens

Create lib/tokens.ts:

import { SignJWT, jwtVerify } from "jose"; const secret = new TextEncoder().encode(process.env.SESSION_SECRET!); export async function sign(payload: Record<string, unknown>, expiresIn: string) { return new SignJWT(payload) .setProtectedHeader({ alg: "HS256" }) .setIssuedAt() .setExpirationTime(expiresIn) .sign(secret); } export async function verify<T = Record<string, unknown>>(token: string): Promise<T | null> { try { const { payload } = await jwtVerify(token, secret); return payload as T; } catch { return null; } } 

Route 1: send the code

Create app/api/otp/send/route.ts:

import { NextRequest, NextResponse } from "next/server"; import Authly from "authly-otp"; import { sign } from "@/lib/tokens"; const authly = new Authly(process.env.AUTHLY_API_KEY!); const E164 = /^\+[1-9]\d{7,14}$/; // Demo-only limiter. In production use Redis (for example Upstash) so it works across serverless instances. const lastSent = new Map<string, number>(); export async function POST(req: NextRequest) { const { phone } = await req.json().catch(() => ({})); if (typeof phone !== "string" || !E164.test(phone)) { return NextResponse.json({ error: "Enter a valid phone number, e.g. +14155552671" }, { status: 400 }); } // 60-second cooldown per phone number const last = lastSent.get(phone) ?? 0; if (Date.now() - last < 60_000) { return NextResponse.json({ error: "Please wait a minute before requesting a new code." }, { status: 429 }); } lastSent.set(phone, Date.now()); try { const { otpId } = await authly.otp.send({ to: phone, channel: "whatsapp", fallbackChannel: "telegram", lang: "en", }); // Keep phone + otpId on the server side of the trust boundary, in a signed cookie const ctx = await sign({ phone, otpId }, "10m"); const res = NextResponse.json({ sent: true }); res.cookies.set("otp_ctx", ctx, { httpOnly: true, secure: process.env.NODE_ENV === "production", sameSite: "lax", path: "/", maxAge: 60 * 10, }); return res; } catch (err) { console.error("OTP send failed", err); return NextResponse.json({ error: "Could not send the code. Please try again." }, { status: 502 }); } } 

Route 2: verify the code and create a session

Create app/api/otp/verify/route.ts:

import { NextRequest, NextResponse } from "next/server"; import Authly from "authly-otp"; import { sign, verify } from "@/lib/tokens"; const authly = new Authly(process.env.AUTHLY_API_KEY!); type Ctx = { phone: string; otpId: string }; export async function POST(req: NextRequest) { const { code } = await req.json().catch(() => ({})); const raw = req.cookies.get("otp_ctx")?.value; const ctx = raw ? await verify<Ctx>(raw) : null; if (!ctx || !/^\d{4,8}$/.test(String(code))) { return NextResponse.json({ error: "Invalid or expired code" }, { status: 400 }); } try { const result = await authly.otp.verify({ otpId: ctx.otpId, code: String(code) }); if (!result.verified) { return NextResponse.json({ error: "Invalid or expired code" }, { status: 400 }); } // Phone is verified: create a 7-day session const session = await sign({ phone: ctx.phone }, "7d"); const res = NextResponse.json({ verified: true }); res.cookies.set("session", session, { httpOnly: true, secure: process.env.NODE_ENV === "production", sameSite: "lax", path: "/", maxAge: 60 * 60 * 24 * 7, }); res.cookies.delete("otp_ctx"); // single use return res; } catch { return NextResponse.json({ error: "Invalid or expired code" }, { status: 400 }); } } 

Things to notice:

  • The client sends only the code. The phone and OTP id come from the signed cookie.
  • Every failure returns the same generic message.
  • The context cookie is deleted after success, so the same verification can't be reused.
  • In production, add attempt limits here too (for example 5 tries per code, tracked in Redis).

The login form

Create app/login/page.tsx:

"use client"; import { useState } from "react"; export default function LoginPage() { const [step, setStep] = useState<"phone" | "code">("phone"); const [phone, setPhone] = useState(""); const [code, setCode] = useState(""); const [message, setMessage] = useState(""); const [busy, setBusy] = useState(false); async function post(url: string, body: object) { setBusy(true); setMessage(""); try { const res = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body), }); const data = await res.json(); if (!res.ok) throw new Error(data.error || "Something went wrong"); return data; } catch (e: any) { setMessage(e.message); return null; } finally { setBusy(false); } } async function sendCode(e: React.FormEvent) { e.preventDefault(); if (await post("/api/otp/send", { phone })) setStep("code"); } async function verifyCode(e: React.FormEvent) { e.preventDefault(); if (await post("/api/otp/verify", { code })) window.location.href = "/dashboard"; } return ( <main style={{ maxWidth: 360, margin: "80px auto", fontFamily: "sans-serif" }}> <h1>Log in</h1> {step === "phone" ? ( <form onSubmit={sendCode}> <label htmlFor="phone">Phone number</label> <input id="phone" type="tel" inputMode="tel" autoComplete="tel" placeholder="+14155552671" value={phone} onChange={(e) => setPhone(e.target.value)} required /> <button disabled={busy}>{busy ? "Sending..." : "Send code"}</button> </form> ) : ( <form onSubmit={verifyCode}> <p>We sent a code to {phone} on WhatsApp.</p> <label htmlFor="code">6-digit code</label> <input id="code" inputMode="numeric" autoComplete="one-time-code" maxLength={6} value={code} onChange={(e) => setCode(e.target.value.replace(/\D/g, ""))} required /> <button disabled={busy}>{busy ? "Checking..." : "Verify"}</button> <button type="button" onClick={() => setStep("phone")}>Change number</button> </form> )} <p role="status" aria-live="polite">{message}</p> </main> ); } 

For more on making this screen convert better (resend timers, auto-submit and error messages), see my post 9 UX Fixes for OTP Verification Screens.

Protect pages with middleware

Create middleware.ts in the project root:

import { NextRequest, NextResponse } from "next/server"; import { verify } from "@/lib/tokens"; export async function middleware(req: NextRequest) { const token = req.cookies.get("session")?.value; const session = token ? await verify(token) : null; if (!session) { return NextResponse.redirect(new URL("/login", req.url)); } return NextResponse.next(); } export const config = { matcher: ["/dashboard/:path*"] }; 

Create a simple app/dashboard/page.tsx to see it work, then run npm run dev, open /login, enter your WhatsApp number, and type the code you receive.

Production checklist

  • Rate limit /api/otp/send per IP and per phone with Redis (for example @upstash/ratelimit). The in-memory Map above doesn't work reliably on serverless platforms.
  • Limit verification attempts per code, then require a new one.
  • Restrict countries you serve, and consider a bot challenge on the login form.
  • Use SameSite and Secure cookies (already set above), and consider rotating SESSION_SECRET safely.
  • Store users in a database after verification, so the phone number maps to an account.
  • Add logout by deleting the session cookie.
  • Handle failed delivery: the fallback channel helps, but also offer "Send via another channel" in the UI.

Wrapping up

The key ideas here are small: keep secrets on the server, never trust the phone number or OTP id from the browser, and use short-lived signed cookies for state. You can adapt the same structure to any provider and any framework.

If you want a version for Pages Router, Remix, Express or Python, tell me in the comments. I'm the maker of Authly, and the docs have the full API reference if you want to try it.

原文:https://www.a8q9.cn/en/article/how-to-add-whatsapp-otp-login-to-a-next-js-app-app-router-with-fallback-and-secu-a1e7df.html

相关文章