Skip to content

Calls & messaging

Validate phone numbers before sending SMS with Twilio

A Twilio Function that checks a number and its line type before sending an SMS, to skip landlines and invalid numbers and limit SMS pumping costs.

Updated 2026-11-26

This recipe puts a phone check in front of every SMS you send with Twilio. A Twilio Function receives the number and the text, asks the API whether the number is valid and what kind of line it is, and calls Twilio's Messages API only when the number can take an SMS and sits in a country you serve. Landlines, invalid numbers and premium-rate lines never cost you a message, and the country list cuts off the destinations that SMS pumping fraud relies on.

There is no Qelka add-on in Twilio's console: the Function calls the API with fetch, which the Node.js runtimes of Twilio Functions include.

What you need

  • A Twilio account with Functions and Assets, and a phone number or Messaging Service allowed to send SMS to your destinations.
  • A Qelka API key. A sk_test_ key returns simulated line data and never spends credits: phone numbers are still parsed for real, so status, e164, country and line_type match a live answer. See Test mode.
  • A key restricted to /phone, created for this Function only. See Restricted keys.

Steps

1. Create the Service and its variables

In the Twilio Console, open Functions and Assets, create a Service, and in the Functions Editor open Settings, then Environment Variables. Add:

Variable Value
QELKA_API_KEY Your Qelka API key
TWILIO_FROM Your Twilio number in E.164, such as +14155550100
FUNCTION_SECRET A long random string your backend sends with each call
ALLOWED_COUNTRIES Countries you send to, as ISO codes: US,CA,GB
PHONE_LEVEL basic, or live to ask the network for the line type

Keep the option that adds your account credentials to the environment turned on: context.getTwilioClient() needs them to return a ready client.

2. Add the Function

Add a Function at the path /send-sms and paste this code:

javascript
const crypto = require('crypto')

const blockedLineTypes = new Set(['landline', 'premium_rate', 'shared_cost', 'toll_free', 'pager', 'uan', 'voicemail'])

function secretMatches(received, expected) {
  if (typeof received !== 'string' || !expected) return false
  const receivedBytes = Buffer.from(received)
  const expectedBytes = Buffer.from(expected)
  return receivedBytes.length === expectedBytes.length && crypto.timingSafeEqual(receivedBytes, expectedBytes)
}

async function checkNumber(context, phone, country) {
  const payload = { phone, level: context.PHONE_LEVEL === 'live' ? 'live' : 'basic' }
  if (country) payload.country = country
  let response
  try {
    response = await fetch('https://api.qelka.com/v1/phone', {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${context.QELKA_API_KEY}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(payload),
      signal: AbortSignal.timeout(4000),
    })
  } catch (error) {
    console.log(`phone check skipped: ${error.name}`)
    return null
  }
  if (!response.ok) {
    const failure = await response.json().catch(() => ({}))
    console.log(`phone check skipped: ${failure.error?.type ?? response.status} request ${response.headers.get('X-Request-Id')}`)
    return null
  }
  return response.json().catch(() => null)
}

function refusalFor(result, allowedCountries) {
  if (result.status === 'unknown') return 'country_needed'
  if (result.status !== 'valid') return 'invalid_number'
  if (allowedCountries.size > 0 && !allowedCountries.has(result.country?.code)) return 'country_not_allowed'
  if (blockedLineTypes.has(result.line_type)) return `line_type_${result.line_type}`
  return null
}

exports.handler = async function (context, event, callback) {
  const response = new Twilio.Response()
  response.appendHeader('Content-Type', 'application/json')
  const reply = (status, body) => {
    response.setStatusCode(status)
    response.setBody(body)
    return callback(null, response)
  }

  if (!secretMatches(event.request?.headers?.['x-function-secret'], context.FUNCTION_SECRET)) {
    return reply(401, { sent: false, reason: 'unauthorized' })
  }

  const to = typeof event.to === 'string' ? event.to.trim() : ''
  const text = typeof event.message === 'string' ? event.message : ''
  if (!to || !text) return reply(400, { sent: false, reason: 'to_and_message_required' })

  const allowedCountries = new Set(
    (context.ALLOWED_COUNTRIES ?? '').split(',').map((code) => code.trim().toUpperCase()).filter(Boolean),
  )
  const country = typeof event.country === 'string' ? event.country : undefined
  const result = await checkNumber(context, to, country)

  let destination = to
  if (result) {
    const refusal = refusalFor(result, allowedCountries)
    if (refusal) return reply(422, { sent: false, reason: refusal })
    destination = result.e164
  }

  try {
    const message = await context.getTwilioClient().messages.create({
      to: destination,
      from: context.TWILIO_FROM,
      body: text,
    })
    return reply(200, { sent: true, sid: message.sid, checked: Boolean(result), line_type: result?.line_type ?? null })
  } catch (error) {
    console.log(`sms not sent: ${error.code ?? error.message}`)
    return reply(502, { sent: false, reason: error.code === 21614 ? 'not_a_mobile_number' : 'twilio_error' })
  }
}

blockedLineTypes lists the line types the Function refuses: lines that usually cannot take an SMS, such as landline, pager and voicemail, and business or premium lines that a personal number should never be, such as premium_rate and toll_free. Adjust it to your traffic: some toll-free numbers can receive SMS, so drop toll_free if you text businesses. The phone reference describes every line type.

To send through a Messaging Service instead of a single number, replace from with messagingServiceSid and store the Service SID in a variable.

3. Deploy and call it

Set the Function's visibility to Public, so your backend can reach it, and click Deploy All. The x-function-secret check keeps strangers out: anyone can see a public URL, but only your backend knows the secret. Twilio passes request headers to Functions with lowercase names, which is why the code reads x-function-secret; header access needs @twilio/runtime-handler 1.2.0 or later in the Service's dependencies.

Call it from your backend, never from a browser or mobile app, since the secret would leak with the code:

bash
curl -X POST "YOUR_FUNCTION_URL" \
  -H "Content-Type: application/json" \
  -H "x-function-secret: $FUNCTION_SECRET" \
  -d '{"to": "(415) 555-0123", "country": "US", "message": "Your order has shipped."}'

The Function sends the SMS to the e164 form of the number, +14155550123 here, so your users can type numbers the way they write them. The country value tells the API how to read a number without a +; send the country of the user's account or address. Without it, a national number comes back unknown and the Function refuses it with country_needed.

If the trigger is a Twilio Studio flow, call the Function from the Run Function widget instead, set its visibility to Protected, and remove the secret check: Twilio then requires a valid X-Twilio-Signature on every request, which Studio sends.

4. Read the answers

Function answer Why What to do
200, sent: true The number passed, or the check was unavailable (checked: false) Nothing
422, invalid_number The number does not exist in its country's numbering plan Ask the user to correct it
422, country_needed No + in the number and no country sent Send country
422, country_not_allowed The number belongs to a country outside ALLOWED_COUNTRIES Refuse, or review the request
422, line_type_landline and others The line type is in blockedLineTypes Offer a voice call or email
502, not_a_mobile_number Twilio refused the number with its error 21614 Treat it like a landline

Choose the level: basic or live

The basic level reads the numbering plan and costs 1 credit. In most countries it tells mobiles from landlines. In the North American Numbering Plan it cannot: US and Canadian numbers come back as fixed_line_or_mobile, because the plan does not separate them. The Function lets those through, and Twilio's own error 21614 catches a landline at send time.

The live level asks the network for the carrier serving the number now and its line type, and costs 3 credits. Set PHONE_LEVEL to live when most of your traffic is North American and a refused landline costs you more than the lookup. A live request is billed even for a number that turns out to be invalid, so when much of your input is junk, the basic level is the better first filter. See the phone reference and Line type lookup.

Handle errors and rate limits

The Function fails open: when the API cannot be reached, times out after 4 seconds, or answers with an error, it logs the error type and the X-Request-Id and sends the SMS anyway, with checked: false. A validation outage then never stops your messages, and Twilio's Geographic Permissions still apply. If you would rather refuse a message you could not check, answer 503 in that branch instead: it is a business decision, not a technical one.

Twilio documents a hard execution limit of 10 seconds for a Function, after which the caller gets a 504; that is Twilio's number and may change. The 4-second timeout and the absence of retries keep the check and the send inside it. Everything happens before callback, because the runtime stops the Function once callback is called.

No API error is billed. 401 invalid_api_key and 403 forbidden mean a wrong or restricted key, 402 insufficient_credits an empty balance: all three end as checked: false, so search the Function's logs for phone check skipped and fix the cause. A key allows 200 requests per 10 seconds; above that, the API answers 429 rate_limited, the Function sends without a check, and a burst that large deserves a look anyway. See Errors and Rate limits.

Results are cached for 7 days, but a cached answer costs the same, so store e164 and line_type with the user's record and skip the check on the next message to the same number.

Frequently asked questions

Twilio has its own Lookup API. Why use this instead?
Twilio Lookup is a good option if Twilio is your only provider. This recipe suits teams that already use Qelka for email, phone or IP checks elsewhere, or send through several providers, and want one check and one set of results everywhere. The Function is the same either way: check first, then call messages.create only when the number passes.
Where does the API key go in a Twilio Function?
In the Service's environment variables: open the Functions Editor, then Settings, then Environment Variables, and add the key under a name such as QELKA_API_KEY. The Function reads it as a property of the context object. Never put it in the code or in a public Asset, where anyone with the URL could read it.
Will this stop SMS pumping?
It removes the easy targets: invalid numbers, premium-rate and other non-mobile lines, and every country outside the list you allow. Pumping can still use valid mobile numbers in countries you accept, so combine it with Twilio's Messaging Geographic Permissions, its SMS Pumping Protection setting, and a limit on how many messages one user or IP can trigger. Our blog post on SMS pumping fraud explains the attack.

More in Calls & messaging

All integrations

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