To send an SMS from NestJS, wrap the provider's REST call in an injectable service, read the API key from ConfigService, and let a queue processor call that service so retries and idempotency stay in one place. The HTTP part is a single fetch.

We make Ready, so the example uses the Ready REST API and only the request shape we document. If you want a typed client that isn't tied to Nest, see our TypeScript client guide.

The service

import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';

export interface SendResult { status: number; text: string }

@Injectable()
export class SmsService {
  constructor(private readonly config: ConfigService) {}

  async send(to: string, body: string, key: string): Promise<SendResult> {
    const res = await fetch('https://api.tryready.com/v1/messages', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-API-Key': this.config.getOrThrow<string>('READY_API_KEY'),
        'Idempotency-Key': key,
      },
      body: JSON.stringify({ to, body, consent_attested: true }),
      signal: AbortSignal.timeout(15_000),
    });
    return { status: res.status, text: await res.text() };
  }
}

getOrThrow makes the app fail at the first send, not silently post with an empty key. to is E.164. Set consent_attested to true only when the recipient agreed to texts. Nest's own HttpModule works too, but on Node 18 and later the built-in fetch is one less dependency.

A BullMQ processor

import { Processor, WorkerHost } from '@nestjs/bullmq';
import { Job, UnrecoverableError } from 'bullmq';

@Processor('sms')
export class SmsProcessor extends WorkerHost {
  constructor(private readonly sms: SmsService) { super(); }

  async process(job: Job<{ to: string; body: string; key: string }>) {
    const { status, text } = await this.sms.send(job.data.to, job.data.body, job.data.key);
    if (status === 429 || status === 500) throw new Error(`retry: ${status}`);
    if (status === 503) throw new UnrecoverableError(`not sent ${status}: resend with a new key`);
    if (status === 409 && text.includes('idempotency_in_progress')) throw new Error(`retry: ${status}`);
    if (status >= 400) throw new UnrecoverableError(`parked ${status}: ${text}`);
    return { sent: true };
  }
}

Add the job with the key created once and with bounded attempts:

await this.queue.add('send', { to, body, key: randomUUID() }, {
  attempts: 5,
  backoff: { type: 'exponential', delay: 1000 },
});

BullMQ re-runs process with the same job.data, so the same Idempotency-Key goes out on every attempt. A repeated key means the request isn't sent twice, which is what makes a retry after a timeout safe. A thrown error means retry, except UnrecoverableError, which sends the job straight to the failed set. So 4xx responses such as a bad number or an opted-out contact are parked there, where you can see and alert on them, instead of being marked done. A 409 QUIET_HOURS_BLOCK is a time rule, so resend it once the window opens. See the retries guide for the whole table.

Where each piece lives

PieceNest homeWhy
HTTP callSmsServiceEasy to mock in tests
Key and policySmsProcessor and job optionsOne place decides retries
SecretConfigServiceNot in the repo
WebhookA controller using the raw bodySignature check needs the exact bytes

For the webhook controller, enable rawBody: true when you create the app, verify the signature, return 200 and enqueue the work. The inbound webhook guide explains why.

FAQ

Should the service call the API directly from a controller?

Only for a one-off the user is waiting on. For anything that must arrive, enqueue it, so a restart or a slow carrier doesn't lose it.

How do I unit test SmsService?

Replace global fetch with a stub, or inject a fake SmsService into the processor. Our mocking guide shows both.

Does it work with Fastify?

Yes, it does. Nothing here depends on Express or Fastify, only on fetch and the queue, so the service and processor carry over unchanged.

The short version

A thin service, a processor that owns retries, and one key per message. The messages API docs list every field.

Cost and registration

A segment on the Standard rate is $0.0075 plus a $0.0045 carrier fee, passed through at cost, excluding optional screening. An account can send up to 500 texts a month before it registers for 10DLC, and most approvals take 2 to 7 days. See pricing for the full list.