Skip to content

Integrations

Validate phone numbers and emails in Bun

Check emails, phone numbers and IPs from a Bun.serve server with the SDK. Reject bad input with a 422, flag risky signups and fail open on API errors.

Updated 2026-11-23

This recipe adds a signup endpoint to a Bun server. It checks the email, the phone number and the client IP with the SDK, answers 422 for clear negatives and lets everything else through.

What you need

  • Bun 1.1 or later.
  • 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 the SDK

bash
bun add @qelka/sdk

2. The validation function

Save as validate-signup.ts:

typescript
import { ApiConnectionError, ApiError, Client } from '@qelka/sdk'

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

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

3. The server

typescript
import { validateSignup } from './validate-signup'

const server = Bun.serve({
  port: 3000,
  async fetch(request, server) {
    const url = new URL(request.url)
    if (request.method !== 'POST' || url.pathname !== '/signup') return new Response('Not found', { status: 404 })

    const body = await request.json().catch(() => null)
    if (!body) return Response.json({ errors: { body: 'Send a JSON body.' } }, { status: 400 })

    const verdict = await validateSignup({
      email: body.email,
      phone: body.phone,
      country: body.country,
      ip: server.requestIP(request)?.address,
    })

    if (Object.keys(verdict.errors).length > 0) return Response.json({ errors: verdict.errors }, { status: 422 })
    return Response.json({ phone: verdict.e164 ?? body.phone, needsReview: verdict.review, needsRecheck: !verdict.checked }, { status: 201 })
  },
})

console.log(`Listening on ${server.url}`)

Run it with bun run server.ts. On a local run the client address is 127.0.0.1, so the IP check answers 422 unprocessable_input, which the function treats as no signal. Keep needsReview and needsRecheck on the account.

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 the SDK run on Bun?
Yes. The SDK uses only the platform fetch and Web Crypto and has no runtime dependencies, so it runs on Bun as well as Node.js, Deno and Cloudflare Workers. You can also skip it and call the API with fetch, since the API is plain HTTPS and JSON.
How do I load the API key?
Bun reads a .env file automatically, so put API_KEY there for development and keep the file out of version control. In production set the variable in your host. Read it with process.env.API_KEY or Bun.env.API_KEY in the server only.
How do I get the client IP in Bun.serve?
The second argument of the fetch handler is the server, and server.requestIP(request) returns the connection address. Behind a proxy that is the proxy, so read the header your platform sets and trust only proxies you control.

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