Verify phone numbers in a Next.js app
Add SMS one-time code verification to a Next.js app with coss.com Verify, two server actions and a fraud guard that stops SMS pumping.
This guide adds SMS one-time code verification to a Next.js App Router app. Verify makes the code, sends it, keeps only a keyed hash of it, counts attempts and expires it; your app makes two calls on the server. The overview is phone verification.
Set up the client
Run npx coss-cli init (or install coss and put a sandbox coss_test_… key in .env.local as
COSS_API_KEY). new Coss() reads the key and refuses to run in a browser: use it only on the server.
Send the code from a server action
coss.verify.start() takes the number in E.164 form (+14155550123) and sends an SMS. Pass the end
user's ip (the address your own proxy vouches for) and your user_id: the
fraud guard uses them. Keep the number on the server (in your session or
database) so the check can't be pointed at another one.
"use server";
import { } from "coss";
import { } from "next/headers";
const = new ();
export type = { : "phone" | "code" | "done"; ?: string };
export async function (: , : ): <> {
const = (.("phone") ?? "").(/[\s()-]/g, "");
const = (await ()).("x-forwarded-for")?.(",")[0]?.();
const { } = await ..({ : , , : await () });
if (!) {
await ();
return { : "code" };
}
switch (.) {
case "verification_blocked":
return { : "phone", : "We can't send a code to this number right now." };
case "recipient_suppressed":
return { : "phone", : "This number opted out. Reply START to us, or use email." };
default:
return { : "phone", : . };
}
}
A blocked verification is stored with its reasons (sent by the verification.blocked webhook);
nothing is sent or billed. Numbers outside the allowed countries fail with country_not_allowed.
Check the code the user typed
coss.verify.check() checks the destination's latest verification. Only valid: true proves the
person has the phone. A wrong code spends an attempt, and the fifth wrong one (by default) fails
the verification: data.verification has attempts, max_attempts and status.
export async function (: , : ): <> {
const = await ();
const = (.("code") ?? "").();
const { , } = await ..({ : , });
if () return { : "code", : . };
if (!.) return { : "code", : "That code didn't work." };
await ();
return { : "done" };
}The form
One client component shows the phone step, then the code step. Prefer route handlers? Call the
same two methods from app/verify/start/route.ts and app/verify/check/route.ts.
"use client";
import { useActionState } from "react";
import { checkCode, sendCode, type VerifyState } from "./actions";
const initial: VerifyState = { step: "phone" };
export function VerifyForm() {
const [sent, send, sending] = useActionState(sendCode, initial);
const [checked, check, checking] = useActionState(checkCode, initial);
if (checked.step === "done") return <p>Your number is verified.</p>;
if (sent.step !== "code")
return (
<form action={send}>
<input name="phone" type="tel" autoComplete="tel" placeholder="+1 415 555 0123" />
<button disabled={sending}>Send code</button>
{sent.message && <p>{sent.message}</p>}
</form>
);
return (
<form action={check}>
<input name="code" inputMode="numeric" autoComplete="one-time-code" />
<button disabled={checking}>Verify</button>
{checked.message && <p>{checked.message}</p>}
</form>
);
}Stop SMS pumping with the fraud guard
SMS pumping is a script requesting codes for numbers whose owners are paid per text. The fraud guard checks every new verification before a code is sent and blocks premium-rate and non-mobile numbers, Tor exit nodes, entries on your Risk lists, and bursts from one IP address or user, to one number prefix, or to prefixes and countries whose codes are rarely entered. Codes go only to the countries in Verify's settings (the US and Canada by default).
Rate limits and resends
To resend, call sendCode again: a new code goes out, the earlier one stops working and the expiry
restarts. A verification sends at most 5 codes, and each destination gets at most 5 every 10
minutes. Codes expire after 10 minutes by default; length, lifetime and attempts are Verify settings
(coss.verify.settings.update()).
Test SMS OTP verification in a sandbox
With a sandbox key nothing reaches a phone, nothing is billed, and the code is always zeros:
await ..({ : "+15005550006" });
const { } = await ..({ : "+15005550006", : "000000" });
.(?.); // trueThe fraud guard still runs: +19005551234 (premium-rate) is blocked (testing).
Fall back to email
For users who can't get a text, pass an email address as to (ada@example.com): the same two
calls send and check a code by email, at no extra cost beyond the verification.
Send live codes
Live SMS needs a paid plan and a sender. While coss.com's shared numbers roll out, set one of your
registered numbers as sms_from in Verify's settings, or live SMS codes fail
with 503 shared_sender_unavailable (SMS codes). See pricing.
Next steps
- Verify: how a verification goes, settings and webhooks
- Fraud guard: every block reason
- Phone checks: line type and carrier before you send a code
- Send SMS with Node.js
Last updated