Integrations
Validate phone numbers and emails in Next.js
Validate emails and phone numbers in a Next.js App Router route handler or Server Action with the official SDK, keeping the API key on the server.
Updated 2026-11-23
This recipe validates a signup form in the Next.js App Router. The check runs in a route handler and a Server Action, so the API key never reaches the browser.
What you need
- Next.js 14 or later with the App Router, and Node.js 20 or later.
- A Qelka API key. Put it in
.env.localasAPI_KEYand in your host's environment variables for production. Do not name it with aNEXT_PUBLIC_prefix: that would expose it to the browser. See Authentication. - A
sk_test_key for development: it returns simulated results and never spends credits. See Test mode.
Steps
1. Install the SDK
npm install @qelka/sdk
2. A shared validation function
import 'server-only'
import { ApiConnectionError, ApiError, Client } from '@qelka/sdk'
const client = new Client({ apiKey: process.env.API_KEY as string, timeoutMs: 8000 })
export type Verdict = {
ok: boolean
errors: Record<string, string>
checked: boolean
e164: string | null
review: boolean
}
export async function validateSignup(input: {
email: string
phone: string
country?: string
ip?: string
}): Promise<Verdict> {
const verdict: Verdict = { ok: true, errors: {}, checked: true, e164: null, review: false }
const settle = async (task: () => Promise<void>) => {
try {
await task()
} catch (error) {
if (error instanceof ApiError && error.type === 'unprocessable_input') return
verdict.checked = false
const detail = error instanceof ApiError ? `${error.type} ${error.requestId}` : String(error)
console.error('validation skipped', detail)
if (!(error instanceof ApiError) && !(error instanceof ApiConnectionError)) throw error
}
}
await settle(async () => {
const result = await client.email.verify({ email: input.email })
if (result.status === 'undeliverable') {
verdict.errors.email = result.did_you_mean
? `Did you mean ${result.did_you_mean}?`
: 'This email address cannot receive mail.'
} else if (result.status === 'risky' && result.reason === 'disposable') {
verdict.review = true
}
})
await settle(async () => {
const result = await client.phone.validate({ phone: input.phone, country: input.country })
if (result.status === 'valid') verdict.e164 = result.e164
if (result.status === 'invalid') verdict.errors.phone = 'This phone number is not valid.'
})
if (input.ip) {
await settle(async () => {
const result = await client.ip.lookup({ ip: input.ip as string })
if (result.risk.level === 'high' || result.flags.tor) verdict.review = true
})
}
verdict.ok = Object.keys(verdict.errors).length === 0
return verdict
}
import 'server-only' makes the build fail if a client component ever imports this file. The SDK retries 429, 502 and 503 on its own, and a call that fails for good only sets checked to false: the signup goes through and you re-check later.
3. A route handler for live validation
Save as app/api/validate/route.ts:
import { headers } from 'next/headers'
import { NextResponse } from 'next/server'
import { validateSignup } from '@/lib/validate-signup'
export async function POST(request: Request) {
const body = await request.json()
const forwarded = (await headers()).get('x-forwarded-for')
const verdict = await validateSignup({
email: String(body.email ?? ''),
phone: String(body.phone ?? ''),
country: body.country,
ip: forwarded?.split(',')[0]?.trim(),
})
return NextResponse.json({ ok: verdict.ok, errors: verdict.errors })
}
Only ok and errors leave the server. Do not return the raw API result to the browser.
4. A Server Action for the form
'use server'
import { validateSignup } from '@/lib/validate-signup'
export async function signUp(_previous: unknown, formData: FormData) {
const verdict = await validateSignup({
email: String(formData.get('email') ?? ''),
phone: String(formData.get('phone') ?? ''),
country: String(formData.get('country') ?? '') || undefined,
})
if (!verdict.ok) return { errors: verdict.errors }
return { errors: {}, phone: verdict.e164 }
}
Use it with useActionState in a client form and render state.errors. Store e164, the normalized number, rather than what the person typed.
5. Read the result
| Result | Action |
|---|---|
Email undeliverable |
Reject and show did_you_mean |
Email risky, reason disposable |
Flag, or reject if you block disposable inboxes |
Email unknown |
Accept and confirm by email |
Phone valid |
Store e164 |
Phone unknown |
No + and no country sent: send the country |
IP high risk or Tor |
Flag for review |
Handle errors and rate limits
401 invalid_api_key and 403 forbidden mean a wrong or restricted key. 402 insufficient_credits means an empty balance: alert yourself and fail open. 429 rate_limited happens above 200 requests per 10 seconds per key, and the SDK waits Retry-After for you. A 422 on an IP is a private address, normal on localhost. Nothing is billed on errors. See Errors and Rate limits.
Related
Frequently asked questions
Can I call the API from a client component?
Route handler or Server Action?
Does this work on the Edge runtime?
Put this check in your product
Get an API key in under a minute. 100 free credits every month, no card required.
- 100 free credits a month
- No card
- Test keys spend nothing
- Cancel any time