# Verify phone numbers in a Next.js app (/docs/guides/phone-verification-nextjs)

This guide adds SMS one-time code verification to a Next.js App Router app. [Verify](/docs/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](/solutions/phone-verification).

## Set up the client [#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 [#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](/docs/verify/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.

```ts twoslash title="app/verify/actions.ts"
"use server";
import { Coss } from "coss";
import { headers } from "next/headers";

const coss = new Coss();

export type VerifyState = { step: "phone" | "code" | "done"; message?: string };

export async function sendCode(_prev: VerifyState, formData: FormData): Promise<VerifyState> {
  const phone = String(formData.get("phone") ?? "").replace(/[\s()-]/g, "");
  const ip = (await headers()).get("x-forwarded-for")?.split(",")[0]?.trim();
  const { error } = await coss.verify.start({ to: phone, ip, user_id: await currentUserId() });
  if (!error) {
    await savePendingPhone(phone);
    return { step: "code" };
  }
  switch (error.code) {
    case "verification_blocked":
      return { step: "phone", message: "We can't send a code to this number right now." };
    case "recipient_suppressed":
      return { step: "phone", message: "This number opted out. Reply START to us, or use email." };
    default:
      return { step: "phone", message: error.message };
  }
}
// ---cut-after---
declare function currentUserId(): Promise<string>;
declare function savePendingPhone(phone: string): Promise<void>;
```

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 [#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`.

```ts twoslash title="app/verify/actions.ts"
import { Coss } from "coss";
const coss = new Coss();
type VerifyState = { step: "phone" | "code" | "done"; message?: string };
declare function pendingPhone(): Promise<string>;
declare function markPhoneVerified(phone: string): Promise<void>;
// ---cut---
export async function checkCode(_prev: VerifyState, formData: FormData): Promise<VerifyState> {
  const phone = await pendingPhone();
  const code = String(formData.get("code") ?? "").trim();
  const { data, error } = await coss.verify.check({ to: phone, code });
  if (error) return { step: "code", message: error.message };
  if (!data.valid) return { step: "code", message: "That code didn't work." };
  await markPhoneVerified(phone);
  return { step: "done" };
}
```

## The form [#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`.

```tsx title="app/verify/verify-form.tsx"
"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 [#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](/docs/risk/lists-and-feedback), 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 [#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 [#test-sms-otp-verification-in-a-sandbox]

With a sandbox key nothing reaches a phone, nothing is billed, and the code is always zeros:

```ts twoslash
import { Coss } from "coss";
const coss = new Coss({ apiKey: "coss_test_…" });
// ---cut---
await coss.verify.start({ to: "+15005550006" });
const { data } = await coss.verify.check({ to: "+15005550006", code: "000000" });
console.log(data?.valid); // true
```

The fraud guard still runs: `+19005551234` (premium-rate) is blocked ([testing](/docs/verify/testing)).

## Fall back to email [#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](/docs/verify/email), at no extra cost beyond the verification.

## Send live codes [#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](/docs/sms/senders) as `sms_from` in Verify's settings, or live SMS codes fail
with `503 shared_sender_unavailable` ([SMS codes](/docs/verify/sms)). See [pricing](/pricing).

## Next steps [#next-steps]

- [Verify](/docs/verify): how a verification goes, settings and webhooks
- [Fraud guard](/docs/verify/fraud-guard): every block reason
- [Phone checks](/docs/risk/lookups): line type and carrier before you send a code
- [Send SMS with Node.js](/docs/guides/send-sms-nodejs)
