Skip to content

Integrations

Validate phone numbers and emails in Astro

Check emails, phone numbers and IPs in an Astro API endpoint or action with the SDK. Reject bad input with a 422, flag risky signups and fail open on errors.

Updated 2026-11-23

This recipe adds a signup endpoint to an Astro site. The email, phone number and client IP are checked on the server, clear negatives get a 422 and an API outage never blocks a signup.

What you need

  • Astro 4 or later with a server adapter for your host (Node.js, Cloudflare, Vercel or Netlify).
  • A Qelka API key in the API_KEY environment variable. A sk_test_ key returns simulated results and never spends credits: see Test mode.
  • The key in a private variable, used only in server code: see Authentication.

Steps

1. Install the SDK

bash
npm install @qelka/sdk

2. The validation module

Save as src/lib/validate-signup.ts:

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

const client = new Client({ apiKey: import.meta.env.API_KEY, 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 endpoint

Save as src/pages/api/signup.ts:

typescript
import type { APIRoute } from 'astro'
import { validateSignup } from '../../lib/validate-signup'

export const prerender = false

export const POST: APIRoute = async ({ request, clientAddress }) => {
  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: clientAddress })

  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 })
}

4. Call it from a form

astro
---
---
<form id="signup">
  <input name="email" type="email" required />
  <input name="phone" type="tel" />
  <p id="error" role="alert"></p>
  <button type="submit">Sign up</button>
</form>

<script>
  const form = document.querySelector<HTMLFormElement>('#signup')!
  const error = document.querySelector<HTMLElement>('#error')!
  form.addEventListener('submit', async (event) => {
    event.preventDefault()
    const body = Object.fromEntries(new FormData(form))
    const response = await fetch('/api/signup', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) })
    const data = await response.json()
    error.textContent = response.status === 422 ? Object.values(data.errors).join(' ') : ''
  })
</script>

The browser talks to your endpoint, never to the API, so the key stays on the server. Put your own rate limit on the endpoint so a bot cannot spend your credits through it. 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

Do I need server rendering?
Yes, for the endpoint. Astro pages can be static, but an endpoint that calls the API needs to run on a server or on a serverless adapter. Mark the route with export const prerender = false, and install the adapter for your host. A static site cannot hold the key safely.
How do I read the API key in Astro?
Use astro:env with a secret server variable, or import.meta.env without the PUBLIC_ prefix, in server code only. Variables with the PUBLIC_ prefix are shipped to the browser, so never use it for the key.
How do I get the client IP?
In an endpoint, the APIContext exposes clientAddress. Some adapters leave it empty or give you the proxy address, so check your adapter and read the header your host sets when needed, trusting 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