Calls & messaging
Validate phone numbers before sending SMS with Vonage
Check a phone number and its line type before sending an SMS with the Vonage Messages API and its Node.js SDK, so landlines and invalid numbers cost nothing.
Updated 2026-11-26
This recipe adds a phone check in front of every SMS you send with the Vonage Messages API. Your server asks Qelka whether the number is valid, which country it belongs to and what kind of line it is, and calls Vonage only when the number can take an SMS. Landlines, invalid numbers and premium-rate lines never cost you a message, and a country allow list cuts off the destinations that SMS pumping fraud targets.
There is no Qelka integration inside the Vonage dashboard: the check runs in your own Node.js code, right before the official Vonage SDK sends the message.
What you need
- A Vonage account with an application that has the Messages capability, its application ID and its private key file (
private.key), and a Vonage number or sender ID you may send from. Vonage's reference notes that alphanumeric sender IDs work for SMS only in some countries. - Node.js 20 or later, for the built-in
fetch. - A Qelka API key, restricted to
/phone. Ask_test_key returns simulated carrier data and never spends credits, but parses numbers for real, sostatus,e164,countryandline_typematch a live answer. See Test mode and Restricted keys.
Steps
1. Install the SDK and set the environment
npm install @vonage/server-sdk @vonage/messages
Set these environment variables on your server, never in code:
| Variable | Value |
|---|---|
QELKA_API_KEY |
Your Qelka API key |
VONAGE_APPLICATION_ID |
The ID of your Vonage application |
VONAGE_PRIVATE_KEY |
The private key itself, or the path to the key file: the SDK accepts both |
VONAGE_FROM |
Your Vonage number in E.164 without the +, such as 14155550100, or a sender ID |
ALLOWED_COUNTRIES |
Countries you send to, as ISO codes: US,CA,GB |
2. Check, then send
const { Vonage } = require('@vonage/server-sdk')
const { SMS } = require('@vonage/messages')
const vonage = new Vonage({
applicationId: process.env.VONAGE_APPLICATION_ID,
privateKey: process.env.VONAGE_PRIVATE_KEY,
})
const blockedLineTypes = new Set(['landline', 'premium_rate', 'shared_cost', 'toll_free', 'pager', 'uan', 'voicemail'])
const allowedCountries = new Set(
(process.env.ALLOWED_COUNTRIES ?? '').split(',').map((code) => code.trim().toUpperCase()).filter(Boolean),
)
async function checkNumber(phone, country, level = 'basic') {
let response
try {
response = await fetch('https://api.qelka.com/v1/phone', {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.QELKA_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(country ? { phone, country, level } : { phone, level }),
signal: AbortSignal.timeout(5000),
})
} catch (error) {
console.warn(`phone check skipped: ${error.name}`)
return null
}
if (!response.ok) {
const failure = await response.json().catch(() => ({}))
console.warn(`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) {
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
}
async function sendCheckedSms({ to, country, text }) {
const result = await checkNumber(to, country)
if (result) {
const refusal = refusalFor(result)
if (refusal) return { sent: false, reason: refusal }
}
const destination = result ? result.e164 : to.trim()
try {
const { messageUUID } = await vonage.messages.send(
new SMS({
to: destination.replace(/^\+/, ''),
from: process.env.VONAGE_FROM,
text,
}),
)
return { sent: true, messageUUID, checked: Boolean(result), e164: result?.e164 ?? null, lineType: result?.line_type ?? null }
} catch (error) {
console.error(`sms not sent: ${error.message}`)
return { sent: false, reason: 'vonage_error' }
}
}
module.exports = { sendCheckedSms }
Call it from your own code, such as an order-shipped job or a signup route:
const { sendCheckedSms } = require('./send-checked-sms')
sendCheckedSms({ to: '(415) 555-0123', country: 'US', text: 'Your order has shipped.' }).then((outcome) => {
console.log(outcome)
})
The SDK's messages.send returns the messageUUID of the accepted message; keep it to match Vonage's message status webhook, which tells you later whether the message was delivered. The phone check returns the number in E.164, +14155550123 here, so users can type it the way they write it. The country value tells the API how to read a number written without a +: pass 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.
3. Act on each outcome
reason |
Why | What to do |
|---|---|---|
none, sent: true |
The number passed, or the check was unavailable (checked: false) |
Store e164 and lineType with the user |
invalid_number |
The number does not exist in its country's numbering plan | Ask the user to correct it |
country_needed |
No + in the number and no country passed |
Pass country |
country_not_allowed |
The number belongs to a country outside ALLOWED_COUNTRIES |
Refuse, or flag the account |
line_type_landline and others |
The line type is in blockedLineTypes |
Offer a voice call or email |
vonage_error |
Vonage refused the request | Read the logged message and Vonage's error |
blockedLineTypes lists lines that usually cannot take an SMS, such as landline, pager and voicemail, and business or premium lines that a personal number should not be, such as premium_rate and toll_free. Adjust it to your traffic; the phone reference describes every line type.
Choose the level: basic or live
The function calls the basic level, 1 credit, which reads the numbering plan. In most countries it separates mobiles from landlines. In the North American Numbering Plan it cannot: US and Canadian numbers come back as fixed_line_or_mobile, which the function lets through, because the plan does not say which they are.
Pass 'live' as the third argument of checkNumber to ask the network instead: it returns the carrier serving the number now, whether it was ported, and the network's line type, for 3 credits. Use it when most of your traffic is North American and an SMS sent to a landline costs you more than the lookup. A live request is billed even when the number turns out not to be valid, so keep basic as the first filter when much of your input is junk. See Line type lookup and Carrier lookup.
Handle errors and rate limits
The check fails open. When the API cannot be reached, times out after 5 seconds, or answers with an error, the function logs the error type and the X-Request-Id and sends the SMS with checked: false. No error is billed. 401 invalid_api_key and 403 forbidden mean a wrong or restricted key, and 402 insufficient_credits an empty balance: all three show up as phone check skipped in your logs, so alert on that line. A 502 upstream_unavailable can only come from the live level; the basic level does not depend on the network provider. See Errors.
A key allows 200 requests per 10 seconds. A campaign that texts thousands of numbers at once will pass it: validate the list beforehand with up to 100 numbers per call to https://api.qelka.com/v1/batch, or as a bulk file, store the results, and send the campaign only to the numbers that passed. See Rate limits.
Results are cached for 7 days, but a cached answer costs the same. Store e164 and the line type with the user's record and skip the check on the next message to the same number.
Related
Frequently asked questions
Why does the code remove the plus sign before sending?
Can I use the older Vonage SMS API instead of the Messages API?
Should the check block the SMS when the API is down?
More in Calls & messaging
All integrationsPut 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