# Next.js

> App Router route handlers that send and check codes, with the pending verification in a signed cookie.

Files (App Router):

```text
lib/otp.ts                    the OTP.ps client (server-only)
lib/otp-session.ts            signs the pending verification into an httpOnly cookie
app/api/otp/send/route.ts     POST { phone, locale }
app/api/otp/check/route.ts    POST { code }
components/OtpForm.tsx        the React form
```

Environment (`.env.local`, never committed):

```bash
OTP_PS_API_KEY=otp_test_…
OTP_SESSION_SECRET=   # 32+ random characters
```

The route handlers are tested against the API's sandbox on every change, including a tampered cookie being refused.

```ts title="examples/nextjs/lib/otp-session.ts"
// Remembers, in a signed httpOnly cookie, which verification this browser is
// waiting for and which number it was sent to. Signed, so the browser can't
// swap in another number; the verification id never reaches page code.
import "server-only";
import { createHmac, timingSafeEqual } from "node:crypto";

export const COOKIE = "otp_pending";

export interface Pending {
  id: string; // OTP.ps verification id
  phone: string; // normalized number the code was sent to
  exp: number; // unix seconds
}

function secret(): string {
  const s = process.env.OTP_SESSION_SECRET;
  if (!s || s.length < 32) throw new Error("OTP_SESSION_SECRET must be set (32+ random characters)");
  return s;
}

const sign = (data: string) => createHmac("sha256", secret()).update(data).digest("base64url");

export function seal(p: Pending): string {
  const data = Buffer.from(JSON.stringify(p)).toString("base64url");
  return `${data}.${sign(data)}`;
}

export function unseal(value: string | undefined): Pending | null {
  if (!value) return null;
  const [data, sig] = value.split(".");
  if (!data || !sig) return null;
  const a = Buffer.from(sig);
  const b = Buffer.from(sign(data));
  if (a.length !== b.length || !timingSafeEqual(a, b)) return null;
  const p = JSON.parse(Buffer.from(data, "base64url").toString()) as Pending;
  return p.exp * 1000 > Date.now() ? p : null;
}
```

```ts title="examples/nextjs/app/api/otp/send/route.ts"
// POST /api/otp/send  { phone, locale? } — called by the OtpForm component.
import { NextResponse, type NextRequest } from "next/server";
import { normalizePhone, OtpError, sendCode } from "../../../../lib/otp";
import { COOKIE, seal } from "../../../../lib/otp-session";

export async function POST(req: NextRequest) {
  const body = (await req.json().catch(() => ({}))) as { phone?: string; locale?: string };
  const locale = body.locale === "en" ? "en" : "ar";
  const phone = normalizePhone(String(body.phone ?? ""));
  if (!phone) {
    return NextResponse.json(
      { error: "invalid_phone", message: locale === "ar" ? "رقم الجوال غير صحيح." : "Please check the mobile number." },
      { status: 400 },
    );
  }
  // Add your own per-IP / per-user limit here (or a CAPTCHA on public forms).
  try {
    const v = await sendCode(phone, { purpose: "verify", locale });
    const res = NextResponse.json({ sent: true, to: v.to, expiresAt: v.expires_at });
    res.cookies.set(COOKIE, seal({ id: v.id, phone, exp: Math.floor(Date.parse(v.expires_at) / 1000) + 60 }), {
      httpOnly: true,
      secure: process.env.NODE_ENV === "production",
      sameSite: "lax",
      path: "/",
      maxAge: 20 * 60,
    });
    return res;
  } catch (e) {
    if (e instanceof OtpError) {
      return NextResponse.json(
        { error: e.code, retryAfter: e.retryAfter },
        { status: e.code === "rate_limited" ? 429 : e.status >= 500 || e.status === 0 ? 503 : 400 },
      );
    }
    throw e;
  }
}
```

```ts title="examples/nextjs/app/api/otp/check/route.ts"
// POST /api/otp/check  { code } — the verification id comes from the signed cookie, not the browser.
import { NextResponse, type NextRequest } from "next/server";
import { checkCode, OtpError } from "../../../../lib/otp";
import { COOKIE, unseal } from "../../../../lib/otp-session";

export async function POST(req: NextRequest) {
  const pending = unseal(req.cookies.get(COOKIE)?.value);
  if (!pending) return NextResponse.json({ error: "no_code" }, { status: 400 });
  const { code } = (await req.json().catch(() => ({}))) as { code?: string };
  try {
    const r = await checkCode(pending.id, String(code ?? ""));
    if (r.valid) {
      const res = NextResponse.json({ verified: true });
      res.cookies.delete(COOKIE);
      // The number is verified: save `pending.phone` on the user or order HERE, on the server.
      return res;
    }
    const res = NextResponse.json({ verified: false, status: r.status, attemptsLeft: r.attempts_left }, { status: 400 });
    if (r.status !== "pending") res.cookies.delete(COOKIE); // expired, failed or replaced: ask for a new code
    return res;
  } catch (e) {
    if (e instanceof OtpError) return NextResponse.json({ error: e.code }, { status: e.status === 404 ? 400 : 503 });
    throw e;
  }
}
```

The client (`lib/otp.ts`) is on the [JavaScript and TypeScript](/docs/examples/javascript-typescript) page, and the form on the [React](/docs/examples/react) page.

Where the comment says *save `pending.phone`*, write the verified number to your user or order in your database. Don't trust anything the browser sends about the number after this point.
