Skip to content

Integrations

Validate phone numbers and emails in Firebase

Validate signups in Firebase with a callable Cloud Function and a blocking beforeUserCreated function. API key in Secret Manager, fail open on errors.

Updated 2026-11-23

This recipe validates signups with two Cloud Functions for Firebase: a callable function your form uses for instant feedback, and a blocking function that enforces the rule on every signup path.

What you need

  • A Firebase project with Cloud Functions (2nd gen), Node.js 20 or later and the Firebase CLI.
  • Outbound network calls from Cloud Functions need the pay-as-you-go Blaze plan, and blocking functions need Identity Platform. Check your plan and Firebase's current requirements.
  • A Qelka API key stored in Secret Manager. A sk_test_ key returns simulated results and never spends credits: see Test mode.

Steps

1. Install and store the secret

bash
cd functions
npm install @qelka/sdk
firebase functions:secrets:set API_KEY

The CLI prompts for the value and stores it in Secret Manager.

2. A shared validation module

Save as functions/validate.js:

javascript
const { ApiConnectionError, ApiError, Client } = require('@qelka/sdk')

async function validateSignup({ email, phone, country, ip }, apiKey) {
  const client = new Client({ apiKey, timeoutMs: 4000, maxRetries: 1 })
  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 (!email) return
      const result = await client.email.verify({ 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 (!phone) return
      const result = await client.phone.validate({ phone, 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
    }),
  ])

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

module.exports = { validateSignup }

mode: 'fast' skips the mailbox check, which keeps the call well inside the time a blocking function allows. See the email reference.

3. A callable function for the form

Save as functions/index.js:

javascript
const { defineSecret } = require('firebase-functions/params')
const { onCall } = require('firebase-functions/v2/https')
const { beforeUserCreated, HttpsError } = require('firebase-functions/v2/identity')
const { validateSignup } = require('./validate')

const apiKey = defineSecret('API_KEY')

exports.validateSignupForm = onCall({ secrets: [apiKey] }, async (request) => {
  const { email, phone, country } = request.data
  const verdict = await validateSignup(
    { email, phone, country, ip: request.rawRequest.ip },
    apiKey.value(),
  )
  return { ok: verdict.ok, errors: verdict.errors, e164: verdict.e164, review: verdict.review }
})

exports.blockBadSignups = beforeUserCreated({ secrets: [apiKey] }, async (event) => {
  const user = event.data
  const verdict = await validateSignup(
    { email: user.email, phone: user.phoneNumber, ip: event.ipAddress },
    apiKey.value(),
  )
  if (verdict.errors.email) {
    throw new HttpsError('invalid-argument', verdict.errors.email)
  }
  if (verdict.review) {
    return { customClaims: { needsReview: true } }
  }
})

The callable function returns only the verdict. The blocking function rejects only a clear negative answer for the email: it checks verdict.errors.email, so an API failure never blocks a signup. A flagged signup gets a needsReview custom claim that your rules or admin tools can read.

Deploy both:

bash
firebase deploy --only functions

4. Call it from the client

javascript
import { getFunctions, httpsCallable } from 'firebase/functions'

const validate = httpsCallable(getFunctions(), 'validateSignupForm')

export async function checkForm(email, phone, country) {
  try {
    const { data } = await validate({ email, phone, country })
    return data
  } catch (error) {
    console.warn('validation unavailable, continuing')
    return { ok: true, errors: {}, e164: null, review: false }
  }
}

If the callable fails, the form continues and the blocking function still has the last word on the email.

5. Read the result

Result Action
Email undeliverable Show the error, or reject in the blocking function
Email risky, reason disposable review is true: flag or reject
Phone valid Store e164
Phone unknown Send country
IP high risk or Tor review is true

Handle errors and rate limits

The SDK retries 429, 502 and 503 once, waiting Retry-After. A key allows 200 requests per 10 seconds. 401 and 403 are key problems, 402 is an empty balance: all fail open and should alert you. No error is billed. See Errors and Rate limits. Turn on Firebase App Check for the callable function so bots cannot spend your credits.

Frequently asked questions

Callable function or blocking function?
Use a callable function when the form should show errors before signup. Use a blocking beforeUserCreated function to enforce a rule on every signup path, including social sign-in. A blocking function can reject the user, but it must finish within a few seconds, so keep calls short and fail open.
Where do I store the API key in Firebase?
In Secret Manager, with firebase functions:secrets:set API_KEY, and bind it to the function through the secrets option. Firebase injects it at runtime as an environment variable. Never put it in client code, Firestore, Remote Config or a committed .env file.
Does this need the Blaze plan?
Calling an external API from Cloud Functions requires outbound network access, which Firebase offers on the pay-as-you-go Blaze plan, not on the free Spark plan. Blocking functions also need Identity Platform. Check Firebase's current pricing and requirements before you build.

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