Skip to content

Integrations

Validate phone numbers and emails in Netlify Functions

Check emails, phone numbers and IPs from a Netlify Function with the SDK. Key in site environment variables, visitor IP from the context, fail open on errors.

Updated 2026-11-23

This recipe adds a Netlify Function that validates a signup: the email, phone number and visitor IP are checked on the server, clear negatives answer 422 and an API outage never blocks a signup. Your form posts to the function, never to the API.

What you need

  • A Netlify site and Node.js 20 or later for functions.
  • A Qelka API key as the API_KEY site environment variable, available to Functions. 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
npm install @qelka/sdk

2. The function

Save as netlify/functions/signup.mjs. Netlify serves it at /.netlify/functions/signup.

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

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

export default async (request, context) => {
  if (request.method !== 'POST') return new Response('Method not allowed', { status: 405 })

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

  const ip = context.ip
  const errors = {}
  const verdict = { checked: true, e164: null, 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
      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 Response.json({ errors }, { status: 422 })
  return Response.json({ phone: verdict.e164 ?? body.phone, needsReview: verdict.review, needsRecheck: !verdict.checked }, { status: 201 })
}

3. Call it from the page

javascript
const response = await fetch('/.netlify/functions/signup', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ email, phone }),
})
const data = await response.json()
if (response.status === 422) showErrors(data.errors)

showErrors is your own function. This uses the modern function format, a default export that receives a Request. Functions have an execution time limit that depends on your plan: check the current value and keep the SDK timeout below it. Run netlify dev to test locally with your environment variables. Add your own rate limit so a bot cannot spend your credits through the endpoint. Store e164 instead of what was typed.

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

Where do I set the API key on Netlify?
In the site settings under Environment variables, or with the Netlify CLI. Scope it to Functions so it is not exposed to the build output, and use a sk_test_ key for deploy previews. Never commit it and never reference it from client code, since anything bundled into the browser is public.
How do I get the visitor IP in a Netlify Function?
The second argument of the function, the context, carries the client address in context.ip. Netlify sets it, so it is safe to use. Do not trust a forwarded header that the client could have sent.
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