OTP verification in React JS and Next.js, with working code
Written and reviewed by the DiOTP team Published 30 November 2026Last updated 30 November 2026
7 min read
This guide shows OTP verification in React JS and in Next.js, from the form a user sees to the server code that checks the digits. You will build one React component with a phone step, a code step and a resend timer, then connect it to two Next.js route handlers that talk to the DiOTP API. The browser only ever calls your own routes. Your API key stays in process.env on the server, and a verified user leaves with an httpOnly session cookie.
Why the API key must stay on the server
Everything in a React bundle is public. Minified code, environment variables baked in at build time and network requests can all be read from the browser's developer tools in seconds. If your DiOTP key were in that bundle, anyone could copy it and send codes to any number, charged to your wallet, until you noticed and revoked it.
So the OTP API React calls is never DiOTP itself. The component posts to routes on your own server, and only that server holds the key. In Next.js this is easy, because route handlers run on the server and can read process.env.DIOTP_API_KEY directly. Do not give the variable a NEXT_PUBLIC_ prefix. That prefix tells Next.js to inline the value into client code, which is exactly what you must avoid.
If your React app is a single-page app with a separate backend, the same rule holds. Build the backend from our OTP verification guide for Node.js and point the form below at it.
How the flow works
- The user types a mobile number and taps "Send code". The form posts it to /api/otp/send.
- The route handler calls DiOTP, stores the request_id in an httpOnly cookie and replies with only a success flag.
- The user types the code from the SMS. The form posts it to /api/otp/verify.
- The handler reads the request_id from the cookie, asks DiOTP to check the code and, on success, sets the session cookie.
DiOTP generates, stores and checks the code, so the digits never pass through your database. A code lasts 5 minutes, allows 5 attempts and can be verified once. The send OTP reference describes every field.
The quick way: Next.js route handlers with the official SDK
The React form below talks only to your own routes, and those routes call DiOTP. The simplest server side is the official Node.js SDK, installed with npm install @diorbit/diotp. It runs only on the server, so the key never reaches the browser:
app/api/otp/send/route.ts
// app/api/otp/send/route.ts
import { DiOTP, DiOTPError } from '@diorbit/diotp'
const diotp = new DiOTP() // reads DIOTP_API_KEY on the server
export async function POST(req: Request) {
const { phone } = await req.json()
try {
const { requestId } = await diotp.send({ to: phone })
return Response.json({ requestId })
} catch (err) {
if (err instanceof DiOTPError) return Response.json({ error: err.code }, { status: err.status ?? 502 })
throw err
}
}app/api/otp/verify/route.ts
// app/api/otp/verify/route.ts
import { DiOTP, DiOTPError } from '@diorbit/diotp'
const diotp = new DiOTP()
export async function POST(req: Request) {
const { requestId, code } = await req.json()
try {
await diotp.verify({ requestId, code: String(code) })
return Response.json({ verified: true }) // set your session cookie here
} catch (err) {
if (err instanceof DiOTPError) return Response.json({ error: err.code }, { status: err.status ?? 502 })
throw err
}
}The sections that follow show the same routes as plain fetch calls to the REST API, the alternative if you prefer no dependency.
A React form for phone OTP
The component below has two steps and handles the details users notice. It disables resend for 30 seconds, which matches DiOTP's resend cooldown. It marks the code input with autoComplete="one-time-code", so iPhones and many Android keyboards offer the code from the incoming SMS with one tap. It also moves focus to the next input when the step changes.
components/OtpForm.tsx
"use client";
import { useEffect, useId, useRef, useState, type FormEvent } from "react";
const MESSAGES: Record<string, string> = {
invalid_phone: "Enter a 10-digit mobile number.",
invalid_code: "That code is not right. Check the SMS and try again.",
expired: "This code has expired. Send a new one.",
too_many_attempts: "Too many wrong tries. Send a new code.",
already_verified: "This code was already used. Send a new one if you need to.",
not_pending: "This code is no longer valid. Send a new one.",
not_found: "We could not find that code. Send a new one.",
no_pending_code: "Ask for a code first.",
resend_cooldown: "Please wait 30 seconds before asking again.",
phone_hourly_limit: "Too many codes for this number. Try again in an hour.",
phone_daily_limit: "Too many codes for this number today. Try again tomorrow.",
trial_restricted: "Test mode only sends to the number you signed up with.",
};
const FALLBACK = "Something went wrong. Please try again in a moment.";
async function post(url: string, body: object) {
const res = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
const data = await res.json().catch(() => ({}));
return { ok: res.ok, error: data.error as string | undefined };
}
export default function OtpForm({ onVerified }: { onVerified: () => void }) {
const [step, setStep] = useState<"phone" | "code">("phone");
const [phone, setPhone] = useState("");
const [code, setCode] = useState("");
const [wait, setWait] = useState(0);
const [busy, setBusy] = useState(false);
const [error, setError] = useState("");
const codeRef = useRef<HTMLInputElement>(null);
const ids = { phone: useId(), code: useId(), hint: useId(), err: useId() };
useEffect(() => {
if (wait <= 0) return;
const t = setTimeout(() => setWait((w) => w - 1), 1000);
return () => clearTimeout(t);
}, [wait]);
useEffect(() => {
if (step === "code") codeRef.current?.focus();
}, [step]);
async function send() {
setBusy(true);
setError("");
const r = await post("/api/otp/send", { phone });
setBusy(false);
if (!r.ok) return setError(MESSAGES[r.error ?? ""] ?? FALLBACK);
setStep("code");
setCode("");
setWait(30);
}
async function verify(e: FormEvent) {
e.preventDefault();
setBusy(true);
setError("");
const r = await post("/api/otp/verify", { code });
setBusy(false);
if (r.ok) return onVerified();
setError(MESSAGES[r.error ?? ""] ?? FALLBACK);
}
const errorText = error ? (
<p id={ids.err} role="alert">{error}</p>
) : null;
if (step === "phone") {
return (
<form onSubmit={(e) => { e.preventDefault(); send(); }} noValidate>
<label htmlFor={ids.phone}>Mobile number</label>
<input
id={ids.phone}
type="tel"
inputMode="numeric"
autoComplete="tel-national"
value={phone}
onChange={(e) => setPhone(e.target.value)}
aria-invalid={Boolean(error)}
aria-describedby={error ? ids.err : undefined}
/>
<button type="submit" disabled={busy}>{busy ? "Sending..." : "Send code"}</button>
{errorText}
</form>
);
}
return (
<form onSubmit={verify} noValidate>
<label htmlFor={ids.code}>6-digit code</label>
<p id={ids.hint}>We sent a code to {phone}. It is valid for 5 minutes.</p>
<input
id={ids.code}
ref={codeRef}
inputMode="numeric"
autoComplete="one-time-code"
maxLength={10}
value={code}
onChange={(e) => setCode(e.target.value.replace(/\D/g, ""))}
aria-invalid={Boolean(error)}
aria-describedby={error ? `${ids.hint} ${ids.err}` : ids.hint}
/>
<button type="submit" disabled={busy || code.length < 4}>Verify</button>
<button type="button" onClick={send} disabled={busy || wait > 0}>
{wait > 0 ? `Resend code in ${wait}s` : "Resend code"}
</button>
<button type="button" onClick={() => { setStep("phone"); setError(""); }}>
Change number
</button>
{errorText}
</form>
);
}The "use client" line marks this as a client component in the Next.js App Router. In a plain React app built with Vite or similar, the line does nothing and you can leave it in or remove it. Either way, the component knows nothing about DiOTP. It only posts to /api/otp/send and /api/otp/verify.
OTP verification in Next.js with route handlers
The App Router turns a file named route.ts into an HTTP endpoint. You need two of them, plus a small helper that every handler shares. Add DIOTP_API_KEY to .env.local for development and to your host's environment settings for production. The helper file imports "server-only", a tiny package that makes the build fail if a client component ever imports it by mistake. Install it with npm install server-only.
lib/diotp.ts
import "server-only";
const API = "https://api-diotp.diorbit.com/v1";
export async function diotp(path: string, body: object, headers: Record<string, string> = {}) {
const res = await fetch(`${API}${path}`, {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.DIOTP_API_KEY}`,
"Content-Type": "application/json",
...headers,
},
body: JSON.stringify(body),
cache: "no-store",
});
const data = await res.json().catch(() => ({}));
return { ok: res.ok, status: res.status, data };
}
const USER_FACING = new Set([
"invalid_code", "expired", "too_many_attempts", "already_verified", "not_pending",
"not_found", "resend_cooldown", "phone_hourly_limit", "phone_daily_limit", "trial_restricted",
]);
// Pass through codes the user can act on; hide account problems behind a generic error.
export function publicError(status: number, data: any) {
const code = data?.error?.code ?? "unknown_error";
if (USER_FACING.has(code)) return { status, body: { error: code } };
console.error("DiOTP error", status, code);
return { status: 502, body: { error: "service_error" } };
}app/api/otp/send/route.ts
import { cookies } from "next/headers";
import { NextResponse } from "next/server";
import { diotp, publicError } from "@/lib/diotp";
export async function POST(request: Request) {
const { phone } = await request.json().catch(() => ({}));
const digits = String(phone ?? "").replace(/\D/g, "").slice(-10);
if (!/^[6-9]\d{9}$/.test(digits)) {
return NextResponse.json({ error: "invalid_phone" }, { status: 400 });
}
const r = await diotp(
"/otp/send",
{ to: digits, country_code: 91, purpose: "login" },
{ "Idempotency-Key": crypto.randomUUID() }
);
if (!r.ok) {
const e = publicError(r.status, r.data);
return NextResponse.json(e.body, { status: e.status });
}
const jar = await cookies();
jar.set("otp_request", JSON.stringify({ id: r.data.request_id, phone: digits }), {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "lax",
path: "/api/otp",
maxAge: 5 * 60,
});
return NextResponse.json({ sent: true });
}app/api/otp/verify/route.ts
import { cookies } from "next/headers";
import { NextResponse } from "next/server";
import { diotp, publicError } from "@/lib/diotp";
import { createSession } from "@/lib/session";
export async function POST(request: Request) {
const { code } = await request.json().catch(() => ({}));
const jar = await cookies();
const pending = jar.get("otp_request")?.value;
if (!pending) return NextResponse.json({ error: "no_pending_code" }, { status: 400 });
const { id, phone } = JSON.parse(pending) as { id: string; phone: string };
const r = await diotp("/otp/verify", { request_id: id, code: String(code ?? "") });
if (!r.ok) {
const e = publicError(r.status, r.data);
return NextResponse.json(e.body, { status: e.status });
}
jar.delete({ name: "otp_request", path: "/api/otp" });
const sessionId = await createSession(phone);
jar.set("session", sessionId, {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "lax",
path: "/",
maxAge: 60 * 60 * 24 * 30,
});
return NextResponse.json({ verified: true });
}The request_id never reaches your JavaScript. It lives in an httpOnly cookie scoped to /api/otp that expires with the code, and the verify handler reads it back. A visitor therefore cannot submit a code against someone else's request. Calling await on cookies() works in both current and older App Router versions, because awaiting a value that is not a promise simply returns it.
The verify OTP reference lists the reply fields. Verifying is free, so you are only charged for sends that reach the network.
Set the session cookie after verify
What a "session" means is up to your app. The verify handler above calls createSession, a function you own, and puts whatever it returns in an httpOnly cookie named session. httpOnly stops page scripts from reading it, secure keeps it on HTTPS in production, and sameSite lax blocks most cross-site form tricks.
lib/session.ts
import "server-only";
import { randomBytes } from "node:crypto";
// Replace this with your real store: a sessions table, Redis, or your auth library.
export async function createSession(phone: string): Promise<string> {
const id = randomBytes(32).toString("hex");
// await db.session.create({ data: { id, phone, createdAt: new Date() } });
void phone;
return id;
}If you already use an auth library, skip this file and call the library's own sign-in function at that point instead. The important part is the order: only after DiOTP replies 200 does the user get a session.
Error messages users understand
The route handlers pass DiOTP's error code to the form, and the form turns each code into a plain sentence. Base the logic on the code, which is stable, not on the message text.
| Code | Message shown in the form |
|---|---|
| invalid_code | That code is not right. Check the SMS and try again. |
| expired | This code has expired. Send a new one. |
| too_many_attempts | Too many wrong tries. Send a new code. |
| already_verified | This code was already used. |
| not_pending | This code is no longer valid. Send a new one. |
| not_found | We could not find that code. Send a new one. |
| resend_cooldown | Please wait 30 seconds before asking again. |
| phone_hourly_limit | Too many codes for this number. Try again in an hour. |
| phone_daily_limit | Too many codes for this number today. Try again tomorrow. |
| trial_restricted | Test mode only sends to the number you signed up with. |
Codes such as unauthorized, account_suspended or api_key_minute_limit describe your account, not the user's input. publicError logs them and returns a generic service_error, so a visitor never learns how your setup works.
Accessibility checklist
An OTP screen is often the first thing a new user sees, and a fiddly one costs sign-ups. The component already covers the basics. Here is what each part does and why it matters.
- Every input has a visible label tied to it with htmlFor, so screen readers announce "Mobile number" or "6-digit code", not just "edit text".
- Errors appear in an element with role="alert", which screen readers read aloud as soon as it changes. The input also sets aria-invalid and points to the error with aria-describedby.
- inputMode="numeric" brings up the number pad on phones without the quirks of type="number", which can drop leading zeros.
- Focus moves to the code input when the step changes, so keyboard and screen reader users do not have to hunt for it.
- A single input is used for the code. Six separate boxes look neat but often break paste, autofill and screen readers.
- The resend button stays in the page while disabled and its label counts down, so everyone can see when it will be ready.
- The hint tells the user where the code went and that it lasts 5 minutes, which helps people who need more time.
Before you go live
New accounts begin in test mode, where free test messages go only to the number verified at sign-up. Build and test against that number, then ask to go live from the dashboard; after a business check the same key works for any Indian mobile number.
Add a per-IP limit and a bot check in front of /api/otp/send before launch. Next.js has no built-in limiter, so use middleware or your host's firewall rules, and read our SMS pumping protection guide for the reasons. Building a mobile app as well? The React Native OTP guide reuses the same backend. The full API lives in the DiOTP documentation.
