Integrations
Validate phone numbers and emails in AWS Lambda
Check emails, phone numbers and IPs from an AWS Lambda function behind API Gateway with the SDK. Key in Secrets Manager or an environment variable, fail open on errors.
Updated 2026-11-23
This recipe validates a signup inside an AWS Lambda function behind API Gateway. The email, phone number and visitor IP are checked before the request reaches your database, and an API outage never blocks a signup.
What you need
- An AWS account, Node.js 20 or later as the Lambda runtime and an API Gateway HTTP API (payload format 2.0) in front of the function.
- A Qelka API key in the function environment as
API_KEY, or in Secrets Manager. Ask_test_key returns simulated results and never spends credits: see Test mode. - Server-side code only: see Authentication.
Steps
1. Install the SDK
npm install @qelka/sdk
Bundle the function with esbuild or your usual tool so the SDK ships in the deployment package.
2. The handler
Save as handler.mjs:
import { ApiConnectionError, ApiError, Client } from '@qelka/sdk'
const client = new Client({ apiKey: process.env.API_KEY, timeoutMs: 8000 })
const reply = (statusCode, body) => ({
statusCode,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
export const handler = async (event) => {
let body
try {
body = JSON.parse(event.isBase64Encoded ? Buffer.from(event.body, 'base64').toString() : event.body ?? '')
} catch {
return reply(400, { errors: { body: 'Send a JSON body.' } })
}
const ip = event.requestContext?.http?.sourceIp
const errors = {}
const verdict = { checked: true, e164: null, 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
verdict.checked = false
console.error('validation skipped', error instanceof ApiError ? `${error.type} ${error.requestId}` : 'unreachable')
}
}
await Promise.all([
body.email &&
settle(async () => {
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') {
verdict.review = true
}
}),
body.phone &&
settle(async () => {
const result = await client.phone.validate({ phone: body.phone, country: body.country })
if (result.status === 'valid') verdict.e164 = result.e164
if (result.status === 'invalid') errors.phone = 'This phone number is not valid.'
}),
ip &&
settle(async () => {
const result = await client.ip.lookup({ ip })
if (result.risk.level === 'high' || result.flags.tor) verdict.review = true
}),
])
if (Object.keys(errors).length > 0) return reply(422, { errors })
return reply(201, { phone: verdict.e164 ?? body.phone, needsReview: verdict.review, needsRecheck: !verdict.checked })
}
3. Set the function up
Set the handler to handler.handler, the timeout to at least 15 seconds and API_KEY in the environment. To read the key from Secrets Manager instead, fetch it once outside the handler and build the client from it:
import { GetSecretValueCommand, SecretsManagerClient } from '@aws-sdk/client-secrets-manager'
const secrets = new SecretsManagerClient({})
const secret = await secrets.send(new GetSecretValueCommand({ SecretId: process.env.SECRET_ID }))
const client = new Client({ apiKey: secret.SecretString, timeoutMs: 8000 })
Top-level await works in an ES module handler (.mjs) on Node.js 20. Keep the client at module level so warm invocations reuse it. Store e164 instead of what was typed. Add throttling on the API Gateway stage so a bot cannot spend your credits through the endpoint.
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.
Related
Frequently asked questions
Where do I store the API key for Lambda?
How do I get the visitor IP behind API Gateway?
What timeout should the function have?
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