Examples
React
A bilingual (Arabic RTL / English) phone verification form with loading, errors, expiry and a resend countdown.
The form calls your backend (/api/otp/send, /api/otp/check): the Next.js, Express, Laravel or Flask examples all provide those two routes. It never sees the API key, the verification id or the code.
What it handles:
- Arabic (right to left) or English, with the number and code inputs left to right.
autocomplete="one-time-code"and a numeric keyboard, so phones offer the code from the message.- A busy state that also stops double clicks (no duplicate, paid sends).
- A 30-second resend countdown, and
retryAfterfrom a rate-limit answer. - Wrong code (tries left), expired, too many tries, and unsupported numbers.
examples/react/OtpForm.tsx
"use client";
// A phone verification form for React (works as a Next.js client component).
// It only talks to YOUR backend (/api/otp/send and /api/otp/check); the OTP.ps
// key stays on the server. Arabic or English, right-to-left when Arabic.
import { useEffect, useRef, useState } from "react";
type Lang = "ar" | "en";
type Step = "phone" | "code" | "done";
const TEXT = {
ar: {
phone: "رقم الجوال (جوال أو Ooredoo)",
send: "أرسل الرمز",
sending: "جارٍ الإرسال…",
code: "رمز التحقق",
sentTo: (to: string) => `أرسلنا رمزاً إلى ${to}`,
verify: "تحقّق",
checking: "جارٍ التحقق…",
resend: "أعد إرسال الرمز",
resendIn: (s: number) => `إعادة الإرسال بعد ${s} ث`,
change: "غيّر الرقم",
done: "تم التحقق من رقمك ✓",
wrong: (left: number) => `الرمز غير صحيح. تبقّى ${left} محاولات.`,
expired: "انتهت صلاحية الرمز. اطلب رمزاً جديداً.",
failed: "محاولات كثيرة. اطلب رمزاً جديداً.",
invalid_phone: "رقم الجوال غير صحيح.",
unsupported_network: "نرسل الرموز لأرقام جوال و Ooredoo فقط.",
rate_limited: "انتظر قليلاً قبل طلب رمز جديد.",
generic: "تعذّر التحقق الآن. حاول مرة أخرى.",
},
en: {
phone: "Mobile number (Jawwal or Ooredoo)",
send: "Send code",
sending: "Sending…",
code: "Verification code",
sentTo: (to: string) => `We sent a code to ${to}`,
verify: "Verify",
checking: "Checking…",
resend: "Resend code",
resendIn: (s: number) => `Resend in ${s}s`,
change: "Change number",
done: "Your number is verified ✓",
wrong: (left: number) => `Wrong code. ${left} tries left.`,
expired: "The code expired. Ask for a new one.",
failed: "Too many tries. Ask for a new code.",
invalid_phone: "Please check the mobile number.",
unsupported_network: "We can only send codes to Jawwal and Ooredoo numbers.",
rate_limited: "Please wait a moment before asking for a new code.",
generic: "Verification isn't available right now. Please try again.",
},
};
const RESEND_SECONDS = 30; // OTP.ps allows one code per number every 30 seconds
export function OtpForm({ lang = "ar", onVerified }: { lang?: Lang; onVerified?: () => void }) {
const t = TEXT[lang];
const [step, setStep] = useState<Step>("phone");
const [phone, setPhone] = useState("");
const [code, setCode] = useState("");
const [to, setTo] = useState("");
const [busy, setBusy] = useState(false); // also blocks double clicks: no duplicate (paid) sends
const [error, setError] = useState<string | null>(null);
const [wait, setWait] = useState(0);
const codeInput = useRef<HTMLInputElement>(null);
useEffect(() => {
if (wait <= 0) return;
const timer = setTimeout(() => setWait((w) => w - 1), 1000);
return () => clearTimeout(timer);
}, [wait]);
async function post(path: string, body: unknown) {
const res = await fetch(path, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
return { ok: res.ok, data: (await res.json().catch(() => ({}))) as Record<string, any> };
}
async function send() {
if (busy || wait > 0) return;
setBusy(true);
setError(null);
try {
const { ok, data } = await post("/api/otp/send", { phone, locale: lang });
if (!ok) {
setError((t as Record<string, any>)[data.error] ?? t.generic);
if (data.retryAfter) setWait(Number(data.retryAfter));
return;
}
setTo(data.to);
setCode("");
setStep("code");
setWait(RESEND_SECONDS);
setTimeout(() => codeInput.current?.focus(), 0);
} catch {
setError(t.generic);
} finally {
setBusy(false);
}
}
async function verify() {
if (busy || !code) return;
setBusy(true);
setError(null);
try {
const { ok, data } = await post("/api/otp/check", { code });
if (ok && data.verified) {
setStep("done");
onVerified?.();
} else if (data.status === "expired" || data.status === "canceled" || data.error === "no_code") {
setError(t.expired);
} else if (data.status === "failed") {
setError(t.failed);
} else if (typeof data.attemptsLeft === "number") {
setError(t.wrong(data.attemptsLeft));
} else {
setError(t.generic);
}
} catch {
setError(t.generic);
} finally {
setBusy(false);
}
}
return (
<div dir={lang === "ar" ? "rtl" : "ltr"} lang={lang} style={{ display: "grid", gap: 12, maxWidth: 360 }}>
{step === "phone" && (
<form onSubmit={(e) => { e.preventDefault(); void send(); }} style={{ display: "grid", gap: 8 }}>
<label htmlFor="otp-phone">{t.phone}</label>
<input id="otp-phone" type="tel" inputMode="tel" autoComplete="tel" dir="ltr" required
placeholder="059X XXX XXX" value={phone} onChange={(e) => setPhone(e.target.value)} />
<button type="submit" disabled={busy || wait > 0}>{busy ? t.sending : wait > 0 ? t.resendIn(wait) : t.send}</button>
</form>
)}
{step === "code" && (
<form onSubmit={(e) => { e.preventDefault(); void verify(); }} style={{ display: "grid", gap: 8 }}>
<p aria-live="polite">{t.sentTo(to)}</p>
<label htmlFor="otp-code">{t.code}</label>
<input id="otp-code" ref={codeInput} inputMode="numeric" autoComplete="one-time-code" dir="ltr"
pattern="[0-9٠-٩]*" maxLength={6} required value={code}
onChange={(e) => setCode(e.target.value.replace(/\s/g, ""))} />
<button type="submit" disabled={busy || !code}>{busy ? t.checking : t.verify}</button>
<button type="button" onClick={() => void send()} disabled={busy || wait > 0}>
{wait > 0 ? t.resendIn(wait) : t.resend}
</button>
<button type="button" onClick={() => { setStep("phone"); setError(null); }} disabled={busy}>{t.change}</button>
</form>
)}
{step === "done" && <p role="status">{t.done}</p>}
{error && <p role="alert" style={{ color: "#b42318" }}>{error}</p>}
</div>
);
}<OtpForm lang="ar" onVerified={() => router.refresh()} />