Skip to content

Integrations

Validate phone numbers and emails in Hono

Add a Hono middleware that checks emails, phone numbers and IPs with the SDK, rejects bad input with a 422 and fails open on API errors. Runs on Node, Bun and Workers.

Updated 2026-11-23

This recipe adds a validation middleware to a Hono app. It checks the email and phone in the JSON body and the client IP, then either answers 422 or lets the request through with a verdict attached.

What you need

  • Hono 4 on Node.js 20 or later, Bun, Deno or Cloudflare Workers.
  • A Qelka API key in the API_KEY environment variable. A sk_test_ key returns simulated results and never spends credits: see Test mode.
  • Server-side code only: see Authentication.

Steps

1. Install

bash
npm install hono @qelka/sdk

2. The middleware

typescript
import { Hono } from 'hono'
import { createMiddleware } from 'hono/factory'
import { ApiConnectionError, ApiError, Client } from '@qelka/sdk'

type Verdict = { checked: boolean; e164: string | null; review: boolean }
type Env = { Variables: { verdict: Verdict; body: Record<string, string> } }

const client = new Client({ apiKey: process.env.API_KEY as string, timeoutMs: 8000 })

export const validateSignup = createMiddleware<Env>(async (c, next) => {
  const body = await c.req.json().catch(() => null)
  if (!body) return c.json({ errors: { body: 'Send a JSON body.' } }, 400)

  const errors: Record<string, string> = {}
  const verdict: Verdict = { checked: true, e164: null, review: false }
  const ip = c.req.header('x-forwarded-for')?.split(',')[0]?.trim()

  const settle = async (task: () => Promise<void>) => {
    try {
      await task()
    } catch (error) {
      if (error instanceof ApiError && error.type === 'unprocessable_input') return
      if (!(error instanceof ApiError) && !(error instanceof ApiConnectionError)) throw error
      verdict.checked = false
      console.error('validation skipped', error instanceof ApiError ? `${error.type} ${error.requestId}` : 'unreachable')
    }
  }

  await Promise.all([
    body.email &&
      settle(async () => {
        const result = await client.email.verify({ email: body.email })
        if (result.status === 'undeliverable') {
          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
        }
      }),
    body.phone &&
      settle(async () => {
        const result = await client.phone.validate({ phone: body.phone, country: body.country })
        if (result.status === 'valid') verdict.e164 = result.e164
        if (result.status === 'invalid') errors.phone = 'This phone number is not valid.'
      }),
    ip &&
      settle(async () => {
        const result = await client.ip.lookup({ ip })
        if (result.risk.level === 'high' || result.flags.tor) verdict.review = true
      }),
  ])

  if (Object.keys(errors).length > 0) return c.json({ errors }, 422)
  c.set('verdict', verdict)
  c.set('body', body)
  await next()
})

3. Use it on a route

typescript
const app = new Hono<Env>()

app.post('/signup', validateSignup, async (c) => {
  const { checked, e164, review } = c.get('verdict')
  const body = c.get('body')
  const user = await createUser({ email: body.email, phone: e164 ?? body.phone, needsReview: review, needsRecheck: !checked })
  return c.json({ id: user.id }, 201)
})

export default app

createUser is your own function. On Node.js serve it with @hono/node-server. The code reads process.env.API_KEY, which exists on Node.js, Bun and Deno: on Workers read the key from c.env and build the client from it. Read the client address from the header your platform sets, such as CF-Connecting-IP on Cloudflare, and trust only proxies you control.

Read the result

Result Action
Email undeliverable Reject with 422, 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: send the country
IP high risk or Tor Flag for review, add friction

Handle errors and rate limits

No error is billed. The SDK retries 429, 502 and 503 responses, waiting Retry-After when present. After 200 requests per 10 seconds on one key you get 429 rate_limited. 401 invalid_api_key and 403 forbidden mean a wrong or restricted key. 402 insufficient_credits means an empty balance: alert yourself and keep failing open. Each email check costs 1 credit. See Errors and Rate limits.

Frequently asked questions

Does it run on every Hono runtime?
Yes. The SDK uses only the platform fetch and Web Crypto, and Hono runs on the same Web standards, so the same code works on Node.js, Bun, Deno and Cloudflare Workers. Only the way you read the API key and the client IP changes between runtimes.
How do I read the key on Cloudflare Workers?
Use a secret and read it from c.env, since Workers have no process.env by default. Create the client inside the handler or cache it per isolate, and keep the key out of wrangler.toml. See the Cloudflare Workers recipe for the full setup.
What happens if the API is down?
The signup goes through. A failed call never produces a form error: only a clear negative answer, such as an undeliverable email or an invalid phone number, rejects the request. The verdict records that the check did not run, so a background job can re-check the account later.

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