Skip to content

Integrations

Validate phone numbers and emails in NestJS

Add a NestJS provider and signup endpoint that check emails, phone numbers and IPs with the SDK, reject bad input with a 422 and fail open on API errors.

Updated 2026-11-23

This recipe adds an injectable validation service and a signup endpoint to a NestJS app. Clear negatives answer 422 with the field errors, and an API outage never blocks a signup.

What you need

  • NestJS 10 or later on Node.js 20 or later, with @nestjs/config.
  • A Qelka API key in the API_KEY environment variable. A sk_test_ key returns simulated results and never spends credits: see Test mode.
  • Server-side code only: see Authentication.

Steps

1. Install

bash
npm install @qelka/sdk @nestjs/config

2. The service

Save as src/validation/validation.service.ts:

typescript
import { Injectable, Logger } from '@nestjs/common'
import { ConfigService } from '@nestjs/config'
import { ApiConnectionError, ApiError, Client } from '@qelka/sdk'

export type Verdict = { errors: Record<string, string>; checked: boolean; e164: string | null; review: boolean }

@Injectable()
export class ValidationService {
  private readonly client: Client
  private readonly logger = new Logger(ValidationService.name)

  constructor(config: ConfigService) {
    this.client = new Client({ apiKey: config.getOrThrow<string>('API_KEY'), timeoutMs: 8000 })
  }

  async signup(input: { email?: string; phone?: string; country?: string; ip?: string }): Promise<Verdict> {
    const verdict: Verdict = { errors: {}, checked: true, e164: null, 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
        verdict.checked = false
        this.logger.warn(`validation skipped ${error instanceof ApiError ? `${error.type} ${error.requestId}` : 'unreachable'}`)
      }
    }

    await Promise.all([
      input.email &&
        settle(async () => {
          const result = await this.client.email.verify({ email: input.email as string })
          if (result.status === 'undeliverable') {
            verdict.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
          }
        }),
      input.phone &&
        settle(async () => {
          const result = await this.client.phone.validate({ phone: input.phone as string, country: input.country })
          if (result.status === 'valid') verdict.e164 = result.e164
          if (result.status === 'invalid') verdict.errors.phone = 'This phone number is not valid.'
        }),
      input.ip &&
        settle(async () => {
          const result = await this.client.ip.lookup({ ip: input.ip as string })
          if (result.risk.level === 'high' || result.flags.tor) verdict.review = true
        }),
    ])
    return verdict
  }
}

3. The controller

typescript
import { Body, Controller, HttpCode, Post, Req, UnprocessableEntityException } from '@nestjs/common'
import type { Request } from 'express'
import { ValidationService } from './validation.service'

@Controller('signup')
export class SignupController {
  constructor(private readonly validation: ValidationService) {}

  @Post()
  @HttpCode(201)
  async create(@Body() body: { email?: string; phone?: string; country?: string }, @Req() request: Request) {
    const verdict = await this.validation.signup({ ...body, ip: request.ip })
    if (Object.keys(verdict.errors).length > 0) throw new UnprocessableEntityException({ errors: verdict.errors })
    return { phone: verdict.e164 ?? body.phone, needsReview: verdict.review, needsRecheck: !verdict.checked }
  }
}

4. Register them

typescript
import { Module } from '@nestjs/common'
import { ConfigModule } from '@nestjs/config'
import { SignupController } from './validation/signup.controller'
import { ValidationService } from './validation/validation.service'

@Module({
  imports: [ConfigModule.forRoot({ isGlobal: true })],
  controllers: [SignupController],
  providers: [ValidationService],
})
export class AppModule {}

In main.ts, call app.set('trust proxy', 1) on the Express instance when you run behind one proxy, so request.ip is the visitor. Add a throttler such as @nestjs/throttler to the route so a bot cannot spend your credits through it. Store e164 instead of what was typed.

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.

Frequently asked questions

Should the client be a provider?
Yes. Wrap the SDK client in an injectable service, read the key through ConfigService, and inject the service wherever you validate. That keeps the key in one place, makes the service easy to replace with a stub in tests, and gives you one spot to add caching or metrics.
How do I get the client IP in NestJS?
Use the Req decorator and read req.ip. Set trust proxy on the underlying Express or Fastify instance to match your deployment, otherwise req.ip is your load balancer. Trust only the proxies you control.
What happens if the API is down?
The signup goes through. A failed call never produces a form error: only a clear negative answer, such as an undeliverable email or an invalid phone number, rejects the request. The verdict records that the check did not run, so a background job can re-check the account later.

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