Skip to content

Integrations

Validate phone numbers and emails in Supabase

Validate signups in Supabase with an Edge Function: check the email and phone before creating the user, using a Function secret and the official SDK.

Updated 2026-11-23

This recipe validates an email and a phone number in a Supabase Edge Function that your signup form calls first. The function holds the API key as a secret and returns only a verdict.

What you need

  • A Supabase project and the Supabase CLI, with Docker for local serving.
  • A Qelka API key stored as a Function secret. A sk_test_ key returns simulated results and never spends credits: see Test mode.
  • Edge Functions are available on Supabase's free plan, but check your plan's limits and Supabase's documentation for current quotas.

Steps

1. Create the function and set the secret

bash
supabase functions new validate-signup
supabase secrets set API_KEY=$API_KEY

The second command reads the value from your shell, so the key never appears in a file. For local serving, put it in supabase/functions/.env, outside version control.

2. The function

Save as supabase/functions/validate-signup/index.ts:

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

const corsHeaders = {
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
}

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

Deno.serve(async (request) => {
  if (request.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders })

  const client = new Client({ apiKey: Deno.env.get('API_KEY') as string, timeoutMs: 8000 })
  const body = await request.json()
  const ip = request.headers.get('x-forwarded-for')?.split(',')[0]?.trim()
  const errors: Record<string, string> = {}
  let checked = true
  let e164: string | null = null
  let 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
      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 })
      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
    }),
  ])

  const ok = Object.keys(errors).length === 0
  return reply({ ok, errors, checked, e164, review })
})

By default an Edge Function requires a valid Supabase JWT, which the browser client sends for you. Keep that default so strangers cannot spend your credits through the function.

3. Call it before signing up

javascript
import { createClient } from '@supabase/supabase-js'

const supabase = createClient(import.meta.env.VITE_SUPABASE_URL, import.meta.env.VITE_SUPABASE_ANON_KEY)

export async function signUp({ email, password, phone, country }) {
  const { data, error } = await supabase.functions.invoke('validate-signup', {
    body: { email, phone, country },
  })
  if (data && data.ok === false) return { errors: data.errors }
  if (error && !data) console.warn('validation unavailable, continuing')
  const { data: session, error: signUpError } = await supabase.auth.signUp({
    email,
    password,
    options: { data: { phone: data?.e164 ?? phone, needs_review: data?.review ?? false } },
  })
  return { session, errors: signUpError ? { form: signUpError.message } : {} }
}

The function answers 200 with ok: false and the field errors, so a rejected signup is data, not an exception. When the function itself is unreachable, the code continues and signs the person up: fail open. Anon keys are public by design, which is why the API key stays in the function.

4. Read the result

Result Action
Email undeliverable Show the error and did_you_mean
Email risky, reason disposable review is true: flag or reject
Phone valid Store e164 in user metadata
Phone unknown Send country
IP high risk or Tor review is true
checked false Accept and re-check later

Handle errors and rate limits

The SDK retries 429, 502 and 503 with Retry-After. A key allows 200 requests per 10 seconds. 401 and 403 are key problems and 402 is an empty balance: all three should alert you and fail open. Nothing is billed on errors. See Errors and Rate limits.

Frequently asked questions

Edge Function or Auth hook?
Use an Edge Function that your frontend calls before supabase.auth.signUp when you want to show errors in the form. Use an Auth hook when you must enforce a rule on every signup path, including ones you do not control. The hook runs inside the signup and can reject it, but the person sees a generic message.
How do I store the API key in Supabase?
As a Function secret, set with the supabase secrets set command or in the dashboard, and read it with Deno.env.get inside the function. Secrets are not part of your code or your client bundle. Never expose the key through a public table, a database setting or a client environment variable.
Can I call the API from the database with pg_net?
You can, but the key would then live in the database, and a trigger that waits for a network call slows every insert. An Edge Function keeps the key in a secret, has retries and timeouts, and returns a clear verdict. Prefer the function, and use the database only to store its results.

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