Skip to content

Integrations

Validate phone numbers and emails in Cloudflare Workers

Check emails, phone numbers and IPs from a Cloudflare Worker with the SDK or fetch. Keep the key as a secret, use the visitor IP header and fail open on errors.

Updated 2026-11-23

This recipe validates a signup request inside a Cloudflare Worker: email, phone and the visitor's IP are checked before the request reaches your origin or your database.

What you need

  • A Cloudflare account and wrangler 3 or later. Workers run on Cloudflare's free plan, but check Cloudflare's current limits on subrequests and CPU time for your plan.
  • A Qelka API key stored as a Worker secret. A sk_test_ key returns simulated results and never spends credits: see Test mode.
  • The Worker as the only holder of the key: see Authentication.

Steps

1. Install the SDK and store the secret

bash
npm install @qelka/sdk
npx wrangler secret put API_KEY

Wrangler asks for the value and stores it encrypted. For wrangler dev, add the same value to a .dev.vars file as API_KEY= followed by your test key, and keep that file out of git.

2. The Worker

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

const json = (data, status = 200) =>
  new Response(JSON.stringify(data), { status, headers: { 'Content-Type': 'application/json' } })

export default {
  async fetch(request, env) {
    if (request.method !== 'POST') return json({ error: 'method_not_allowed' }, 405)

    const client = new Client({ apiKey: env.API_KEY, timeoutMs: 6000, maxRetries: 1 })
    const body = await request.json()
    const ip = request.headers.get('CF-Connecting-IP')
    const errors = {}
    let checked = true
    let e164 = null
    let review = false

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

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

    if (Object.keys(errors).length > 0) return json({ ok: false, errors }, 422)
    return json({ ok: true, checked, e164, review })
  },
}

The three checks run in parallel, so the whole request takes as long as the slowest call. mode: 'fast' skips the mailbox check and runs the syntax, DNS and list checks, which keeps the call short at the edge; use full when you can wait for the mail server. See the email reference.

3. Configure and deploy

wrangler.toml:

name = "validate-signup"
main = "src/index.js"
compatibility_date = "2026-11-01"
bash
npx wrangler deploy

Call it from your form:

bash
curl -X POST https://validate-signup.example.workers.dev \
  -H "Content-Type: application/json" \
  -d '{"email": "jane@example.com", "phone": "+14155550123"}'

4. Read the result

Result Action
Email undeliverable The Worker answers 422 with the message
Email risky, reason disposable review is true: flag or reject
Phone valid e164 is returned: store it
Phone unknown No + and no country: send the country
IP high risk or Tor review is true
Any failure checked is false: accept, re-check later

Handle errors and rate limits

The SDK retries 429, 502 and 503 once here, waiting Retry-After; raise maxRetries if your Worker has time. A key is limited to 200 requests per 10 seconds. 401 and 403 mean a wrong or restricted key, 402 means an empty balance: both fail open and should alert you. Nothing is billed on errors. See Errors and Rate limits. Add Cloudflare rate limiting rules in front of the Worker so bots cannot spend your credits.

Frequently asked questions

Does the SDK run on Cloudflare Workers?
Yes. The SDK uses only the platform fetch and Web Crypto, so it runs on Workers as well as Node.js, Deno and Bun. It has no runtime dependencies. You can also skip it and call the API with fetch, since the API is plain HTTPS and JSON with a single Authorization header.
Where do I store the API key in a Worker?
As a secret, with wrangler secret put API_KEY, and read it from the env binding in your handler. For local development put it in a .dev.vars file that stays out of version control. Never put it in wrangler.toml vars or in code, since both are visible to anyone with repository access.
How do I get the visitor's IP in a Worker?
Cloudflare sets the CF-Connecting-IP header on every request that reaches your Worker. Read it with request.headers.get and pass it to the IP lookup. Do not trust X-Forwarded-For, which a client can set to any value. Local wrangler dev sessions may give you a loopback address, which the API answers with a 422.

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