Developer Quick-Start: Learn how to build TCPA-compliant SMS marketing campaigns with NestJS 11, MessageBird API, and PostgreSQL. Complete guide covering subscriber management, webhook handling, opt-in/opt-out compliance, and production deployment with Prisma ORM. Want to skip 10DLC vetting queues, carrier surcharges, and multi-step SDK boilerplate? You can send the same SMS directly via SMSRoute's REST API with instant no-KYC provisioning.
Learn how to build production-ready SMS marketing campaigns using NestJS 11, MessageBird API (now Bird), and PostgreSQL. This comprehensive tutorial walks you through creating a scalable SMS marketing system with Node.js v16+, complete with TCPA compliance features, webhook handling, and subscriber management using Prisma ORM. You'll learn how to set up your project, implement core logic with Prisma ORM, handle webhooks for subscriber management, and deploy a TCPA-compliant system that manages SMS subscriptions (opt-in/opt-out) and broadcasts messages effectively while maintaining compliance with U.S. telecommunications regulations.
By the end of this tutorial, you'll have a scalable and secure NestJS application that handles incoming SMS commands (SUBSCRIBE/STOP) via MessageBird webhooks and sends targeted marketing messages through an administrative API endpoint. This guide provides a solid foundation, but achieving true "production-ready" status requires further hardening around security (implementing webhook signing key verification), robust error reporting, TCPA compliance, and strategies for very large scale (using job queues).
Important Compliance Note: If you send SMS marketing messages to U.S. consumers, you must comply with the Telephone Consumer Protection Act (TCPA). New TCPA rules became effective April 11, 2025, requiring express written consent, faster opt-out processing (within 10 business days), and acceptance of various opt-out methods. Non-compliance can result in penalties of $500β$1,500 per violation. Consult with legal counsel to ensure your implementation meets all regulatory requirements. [Source: FCC TCPA Rules, effective April 11, 2025]
What You'll Build: SMS Marketing Campaign System Overview
The Challenge: Businesses need a reliable, TCPA-compliant way to manage SMS marketing campaigns, handle subscriber opt-ins and opt-outs automatically, send bulk messages to targeted audiences, and maintain compliance with U.S. telecommunications regulations including the April 2025 TCPA updates.
Solution: Build a NestJS application that:
- Listens for incoming SMS messages via a MessageBird webhook.
- Processes SUBSCRIBE and STOP keywords to manage user subscription status in a database.
- Sends confirmation messages back to the user upon status changes.
- Provides a secure API endpoint for administrators to send broadcast messages to all active subscribers.
- Maintains compliance with TCPA regulations including proper consent management and opt-out handling.
Technologies:
- Node.js: The runtime environment (Node.js v16 or higher required for NestJS v10+).
- NestJS: A progressive Node.js framework for building efficient, reliable, and scalable server-side applications. Its modular architecture, dependency injection, and built-in tooling (validation pipes and Swagger integration) accelerate development and promote maintainability. Latest version: NestJS v11 (released January 2025) with enhanced console logging, performance optimizations, and improved microservice transporters. [Source: NestJS Official Release, January 2025]
- MessageBird (Bird): The communications platform providing the SMS API, virtual mobile numbers (VMNs), and webhook capabilities. Note: MessageBird rebranded to "Bird" but the API endpoints and SDKs remain compatible. [Source: Bird Platform Documentation, 2024]
- PostgreSQL: A powerful, open-source relational database for persistent storage of subscriber data.
- Prisma: A next-generation Object-Relational Mapper (ORM) for Node.js and TypeScript, simplifying database access, migrations, and type safety. Latest version: Prisma ORM v6.2.0 (released January 7, 2025) with stabilized driverAdapters, enhanced full-text search, and AI coding assistant safety checks. [Source: Prisma GitHub Releases, January 2025]
- Docker: For containerizing the application, ensuring consistent environments and simplifying deployment.
System Architecture:
Note: This diagram uses ASCII art for simplicity. In environments supporting it (like GitHub Markdown), a Mermaid diagram could provide a richer visual representation.
+----------+ +-------------+ +---------------+ +-----------------+ +----------+
| User SMS | ----> | MessageBird | ----> | Flow Builder | ----> | NestJS Webhook | ----> | Database |
| (SUB/STOP)| | (VMN) | | (Forward URL) | ----> | (/webhooks/mb) | <---> | (Postgres)|
+----------+ +-------------+ +---------------+ | - Parse Command | +----------+
| - Update Sub |
| - Send Confirm |
+--------+--------+
|
v
+-----------+ +-----------------+ +-----------------+ +-------------+ +----------+
| Admin | ----> | NestJS API | ----> | NestJS Service | ----> | MessageBird | ----> | User SMS |
| (API Call)| | (/campaigns/send| ----> | - Get Subs | ----> | (Send Bulk) | | (Campaign)|
+-----------+ | Auth + Rate L.)| | - Call MB API | +-------------+ +----------+
+-----------------+ +--------+--------+
^
|
+---------------------------------------+
Prerequisites:
- Node.js (LTS version recommended, v16 or higher required) and npm or yarn installed.
- Docker and Docker Compose installed.
- A MessageBird account with API credentials and a purchased Virtual Mobile Number (VMN) with SMS capabilities.
- Access to a PostgreSQL database (local instance via Docker or a cloud provider).
- Basic understanding of TypeScript, REST APIs, and asynchronous programming.
- Legal consultation for TCPA compliance if targeting U.S. consumers.
- localtunnel or ngrok installed globally (for local development testing only): npm install -g localtunnel. These tools are not suitable or reliable for production environments.
Final Outcome:
A containerized NestJS application deployable to various environments, featuring:
- Webhook endpoint for MessageBird SMS events.
- Database persistence for subscriber management.
- API endpoint for sending campaigns.
- Configuration management, logging, basic security, and error handling.
- Setup for monitoring and testing.
Step 1: NestJS Project Setup and Configuration for SMS Marketing
Initialize your NestJS project and install necessary dependencies for SMS marketing.
- Install NestJS CLI:
npm install -g @nestjs/cli
- Create New Project:
nest new messagebird-campaign-app
cd messagebird-campaign-app
Choose your preferred package manager (npm or yarn).
- Project Structure: NestJS creates a standard structure (
src/withapp.module.ts,app.controller.ts,app.service.ts,main.ts). Organize your features into modules (e.g.,SubscribersModule,WebhooksModule,CampaignsModule,MessageBirdModule,DatabaseModule). This promotes separation of concerns and maintainability.
- Install Dependencies:
npm install @nestjs/config
npm install messagebird
npm install prisma @prisma/client pg
npm install -D prisma
npm install libphonenumber-js
npm install @nestjs/swagger swagger-ui-express class-validator class-transformer
npm install helmet @nestjs/throttler
npm install @nestjs/terminus @nestjs/axios
npm install @nestjs/cache-manager cache-manager
npm install async-retry
Note: libphonenumber-js is essential for validating and normalizing international phone numbers in E.164 format as required by MessageBird API. [Source: libphonenumber-js npm package documentation]
- Initialize Prisma:
npx prisma init --datasource-provider postgresql
This creates a prisma directory with a schema.prisma file and a .env
file for the database connection string.
- Configure Environment Variables (
.env): Update the.envfile created by Prisma. Add placeholders for MessageBird credentials and application settings. Create a.env.examplefile to track required variables.
.env (and .env.example): .env
# Database
# Example: postgresql://user:password@host:port/database?schema=public
DATABASE_URL="postgresql://your_db_user:your_db_password@localhost:5432/mb_campaigns?schema=public"
# MessageBird
MESSAGEBIRD_API_KEY="YOUR_MESSAGEBIRD_LIVE_API_KEY"
# Your purchased Virtual Mobile Number (VMN) in E.164 format
MESSAGEBIRD_ORIGINATOR="+12025550181"
# Application
PORT=3000
# Webhook Security (CRITICAL for Production)
# MessageBird uses HMAC-SHA256 signature verification
# Find/Generate in MessageBird Dashboard: Developers > API Access > Signing Key
MESSAGEBIRD_WEBHOOK_SIGNING_KEY="YOUR_SECURE_RANDOM_SIGNING_KEY"
# Simple shared secret for local testing/basic auth (Less Secure β not recommended)
# WEBHOOK_SECRET="YOUR_SECURE_RANDOM_SECRET"
# Admin API Basic Auth Credentials (CHANGE THESE DEFAULTS!)
ADMIN_USER="admin"
ADMIN_PASSWORD="password" # CHANGE THIS!
# PostgreSQL Credentials for Docker Compose (if using .env file)
POSTGRES_USER="your_db_user"
POSTGRES_PASSWORD="your_db_password" # CHANGE THIS!
DATABASE_URL: Connection string for your PostgreSQL database. Replace placeholders. Ensure it uses double quotes as shown.MESSAGEBIRD_API_KEY: Find this in your MessageBird Dashboard under Developers > API access > Live API Key.MESSAGEBIRD_ORIGINATOR: The VMN you purchased from MessageBird (Numbers section), in E.164 format (e.g., +1β¦).PORT: Port the NestJS application runs on.MESSAGEBIRD_WEBHOOK_SIGNING_KEY: Critical for production webhook security. MessageBird signs webhook requests using HMAC-SHA256. The signature includes the request timestamp, URL, and body hash, protecting against tampering and replay attacks. Generate or find your signing key in the MessageBird Dashboard. [Source: Bird API Webhook Verification Documentation, 2024]ADMIN_USER/ADMIN_PASSWORD: Credentials for the Basic Auth guard on the admin endpoint. Change the defaults immediately and use strong credentials.POSTGRES_USER/POSTGRES_PASSWORD: Used by Docker Compose if sourcing from a .env file.
- Configure
ConfigModule: Import and configureConfigModuleinsrc/app.module.tsto load environment variables.
src/app.module.ts:
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { DatabaseModule } from './database/database.module';
import { SubscribersModule } from './subscribers/subscribers.module';
import { WebhooksModule } from './webhooks/webhooks.module';
import { CampaignsModule } from './campaigns/campaigns.module';
import { MessageBirdModule } from './messagebird/messagebird.module';
import { ThrottlerModule } from '@nestjs/throttler';
import { HealthModule } from './health/health.module';
import { CacheModule } from '@nestjs/cache-manager';
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
envFilePath: '.env',
}),
ThrottlerModule.forRoot([{
ttl: 60000,
limit: 10,
}]),
CacheModule.register({
isGlobal: true,
ttl: 60000,
}),
DatabaseModule,
SubscribersModule,
MessageBirdModule,
WebhooksModule,
CampaignsModule,
HealthModule,
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
Step 2: Database Schema Design and Prisma ORM Integration
Store and manage subscriber information with Prisma ORM and PostgreSQL.
- Define Database Schema (
prisma/schema.prisma): Define theSubscribermodel.
prisma/schema.prisma: Prisma
// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model Subscriber {
id String @id @default(cuid()) // Unique identifier
phoneNumber String @unique // E.164 format, unique constraint
isSubscribed Boolean @default(false) // Subscription status
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
- Apply Database Migrations:
- Ensure your PostgreSQL database is running (e.g., via Docker: docker run --name postgres-mb -e
POSTGRES\_PASSWORD=your\_db\_password -e POSTGRES\_USER=your\_db\_user -e POSTGRES\_DB=mb\_campaigns -p
5432:5432 -d postgres) Note: For improved security even locally, avoid hardcoding passwords directly.
Consider using environment variables passed to the
docker runcommand (e.g.,-e POSTGRES_PASSWORD=$DB_PASSWORD) or Docker Compose with a.envfile. - Run the migration command:
npx prisma migrate dev --name init-subscribers
This creates the Subscriber table in your database and generates the Prisma Client.
- Create Database Module (
src/database): A dedicated module for Prisma Client.
src/database/prisma.service.ts:
import { Injectable, OnModuleInit, OnModuleDestroy, Logger } from '@nestjs/common';
import { PrismaClient } from '@prisma/client';
@Injectable()
export class PrismaService extends PrismaClient implements OnModuleInit, OnModuleDestroy {
private readonly logger = new Logger(PrismaService.name);
constructor() {
super({
});
}
async onModuleInit() {
try {
await this.$connect();
this.logger.log('Database connected successfully');
} catch (error) {
this.logger.error('Database connection failed', error);
}
}
async onModuleDestroy() {
await this.$disconnect();
this.logger.log('Database connection closed');
}
}
`src/database/database.module.ts`:
import { Module, Global } from '@nestjs/common'; import { PrismaService } from './prisma.service';
@Global() // Make PrismaService available globally without importing DatabaseModule everywhere @Module({ providers: [PrismaService], exports: [PrismaService], // Export PrismaService for injection }) export class DatabaseModule {}
* `DatabaseModule` is already imported in `src/app.module.ts`.
- Create Subscribers Module (
src/subscribers): Generate the module and service.
nest g module subscribers nest g service subscribers --no-spec nest g controller subscribers --no-spec
*Note: Although we generate a controller here, we will remove it later (in Section 2.6) as subscriber management is handled solely via the MessageBird webhook in this specific application design, not a direct API.*
- Implement
SubscribersService(src/subscribers/subscribers.service.ts): Add logic to interact with the database.
`src/subscribers/subscribers.service.ts`:
import { Injectable, Logger, Inject } from '@nestjs/common'; import { PrismaService } from '../database/prisma.service'; import { Subscriber } from '@prisma/client'; import { CACHE_MANAGER, Cache } from '@nestjs/cache-manager';
@Injectable() export class SubscribersService { private readonly logger = new Logger(SubscribersService.name); private readonly activeSubscribersCacheKey = 'active-subscribers-list';
constructor( private readonly prisma: PrismaService, @Inject(CACHE_MANAGER) private cacheManager: Cache, // Inject Cache Manager ) {}
/**
- Error Handling Strategy: This service catches errors during DB operations and returns
nullor[]. This allows the calling function (e.g., webhook handler) to log the- failure but continue its flow gracefully (e.g., still return 200 OK to MessageBird).
- In other scenarios, throwing specific custom exceptions might be preferred for more
- detailed error handling upstream or via global exception filters.
*/
// Find or create a subscriber, then update status async handleSubscriptionUpdate(phoneNumber: string,
subscribe: boolean): Promise<Subscriber | null> {
this.logger.log(Handling subscription update for ${phoneNumber}. Subscribe: ${subscribe}); try {
const subscriber = await this.prisma.subscriber.upsert({ where: { phoneNumber: phoneNumber }, update: {
isSubscribed: subscribe }, create: { phoneNumber: phoneNumber, isSubscribed: subscribe }, });
this.logger.log(Subscription status updated for ${phoneNumber} to ${subscriber.isSubscribed});
// Invalidate cache on any subscription change await this.cacheManager.del(this.activeSubscribersCacheKey);
this.logger.log(Invalidated active subscribers cache.);
return subscriber; } catch (error) {
this.logger.error(Failed to update subscription for ${phoneNumber}: ${error.message},
error.stack); return null; // Return null on failure as per strategy } }
// Get all active subscribers (potentially from cache) async findActiveSubscribers():
Promise<Pick<Subscriber, 'phoneNumber'>[]> { try { // Try fetching from cache first const
cachedSubscribers = await this.cacheManager.get<Pick<Subscriber,
'phoneNumber'>[]>(this.activeSubscribersCacheKey); if (cachedSubscribers) {
this.logger.log(Fetched ${cachedSubscribers.length} active subscribers from cache.); return
cachedSubscribers; }
// If not in cache, fetch from DB this.logger.log('Cache miss. Fetching active subscribers from
database...'); const activeSubs = await this.prisma.subscriber.findMany({ where: { isSubscribed: true },
select: { phoneNumber: true }, // Only select the phone number });
this.logger.log(Found ${activeSubs.length} active subscribers in database.);
// Store in cache before returning await this.cacheManager.set(this.activeSubscribersCacheKey, activeSubs);
// Use default TTL from CacheModule config
this.logger.log(Stored ${activeSubs.length} active subscribers in cache.);
return activeSubs; } catch (error) {
this.logger.error(Failed to fetch active subscribers: ${error.message}, error.stack); return [];
// Return empty array on error } }
// Find a single subscriber by phone number (useful for checks) async findSubscriberByNumber(phoneNumber:
string): Promise<Subscriber | null> { try { return await this.prisma.subscriber.findUnique({ where: {
phoneNumber: phoneNumber }, }); } catch (error) {
this.logger.error(Failed to find subscriber ${phoneNumber}: ${error.message}, error.stack);
return null; } } }
* Uses `upsert` for efficiency.
* `findActiveSubscribers` retrieves only phone numbers and uses caching.
* Includes logging and cache invalidation.
- Update
SubscribersModule(src/subscribers/subscribers.module.ts): Remove the controller and ensure the service is exported.
src/subscribers/subscribers.module.ts:
import { Module } from '@nestjs/common';
import { SubscribersService } from './subscribers.service';
@Module({
providers: [SubscribersService],
exports: [SubscribersService],
})
export class SubscribersModule {}
- SubscribersModule is already imported into src/app.module.ts.
Step 3: MessageBird SMS API Integration and Webhook Configuration
Handle incoming SMS messages via MessageBird webhooks and implement subscription management.
3.1 Setting Up MessageBird Webhooks for Inbound SMS
- Create Webhooks Module (
src/webhooks):
nest g module webhooks
nest g controller webhooks --no-spec
- Define Webhook DTO (
src/webhooks/dto/messagebird-webhook.dto.ts): Useclass-validatorto validate the incoming payload structure.
src/webhooks/dto/messagebird-webhook.dto.ts:
import { IsString, IsNotEmpty, IsOptional, Matches } from 'class-validator';
export class MessageBirdWebhookDto {
@IsString()
@IsOptional()
id?: string;
@IsString()
@IsNotEmpty()
@Matches(/^\+?[1-9]\d{1,14}$/)
originator: string;
@IsString()
@IsNotEmpty()
payload: string;
@IsString()
@IsOptional()
recipient?: string;
@IsString()
@IsOptional()
type?: string;
@IsString()
@IsOptional()
createdDatetime?: string;
}
Note: Added common optional fields. Adjust based on actual MessageBird payloads and your needs.
- Implement Webhook Controller (
src/webhooks/webhooks.controller.ts):
src/webhooks/webhooks.controller.ts:
import { Controller, Post, Body, HttpCode, HttpStatus, Logger, UsePipes, ValidationPipe, Inject, forwardRef, Req, BadRequestException } from '@nestjs/common';
import { Request } from 'express';
import { SubscribersService } from '../subscribers/subscribers.service';
import { MessageBirdWebhookDto } from './dto/messagebird-webhook.dto';
import { MessageBirdService } from '../messagebird/messagebird.service';
import { parsePhoneNumberFromString } from 'libphonenumber-js';
@Controller('webhooks')
export class WebhooksController {
private readonly logger = new Logger(WebhooksController.name);
constructor(
private readonly subscribersService: SubscribersService,
@Inject(forwardRef(() => MessageBirdService))
private readonly messageBirdService: MessageBirdService,
) {}
@Post('messagebird')
@HttpCode(HttpStatus.OK)
@UsePipes(new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true, transform: true }))
async handleMessageBirdWebhook(
@Body() webhookDto: MessageBirdWebhookDto,
@Req() request: Request
) {
this.logger.log(`Received MessageBird webhook. Originator: ${webhookDto.originator}, Payload: ""${webhookDto.payload}""`);
const phoneNumber = parsePhoneNumberFromString(webhookDto.originator);
if (!phoneNumber || !phoneNumber.isValid()) {
this.logger.warn(`Received webhook with invalid originator format: ${webhookDto.originator}`);
return { message: 'Webhook received (invalid originator ignored)' };
}
const normalizedOriginator = phoneNumber.format('E.164');
const keyword = webhookDto.payload.trim().toLowerCase();
let confirmationMessage: string | null = null;
try {
if (keyword === 'subscribe') {
const subscriber = await this.subscribersService.handleSubscriptionUpdate(normalizedOriginator, true);
if (subscriber) {
confirmationMessage = 'Thanks for subscribing! Text STOP to opt-out.';
this.logger.log(`User ${normalizedOriginator} subscribed.`);
} else {
this.logger.warn(`Subscription update failed for ${normalizedOriginator} (subscribe)`);
}
} else if (keyword === 'stop') {
const subscriber = await this.subscribersService.handleSubscriptionUpdate(normalizedOriginator, false);
if (subscriber) {
confirmationMessage = 'You have unsubscribed. Text SUBSCRIBE to rejoin.';
this.logger.log(`User ${normalizedOriginator} unsubscribed.`);
} else {
this.logger.warn(`Subscription update failed for ${normalizedOriginator} (stop)`);
}
} else {
this.logger.log(`Received unknown keyword ""${keyword}"" from ${normalizedOriginator}. Ignoring.`);
}
if (confirmationMessage) {
this.messageBirdService.sendMessage(normalizedOriginator, confirmationMessage)
.then(() => this.logger.log(`Sent confirmation to ${normalizedOriginator}`))
.catch(err => this.logger.error(`Failed to send confirmation to ${normalizedOriginator}: ${err.message}`, err.stack));
}
} catch (error) {
this.logger.error(`Error processing webhook from ${normalizedOriginator}: ${error.message}`, error.stack);
}
return { message: 'Webhook received' };
}
}
- Responds 200 OK quickly.
- Uses ValidationPipe.
- Normalizes phone number and keyword.
- Calls SubscribersService.
- Calls MessageBirdService asynchronously for confirmations.
- Includes strong comments emphasizing the need for production signing key verification.
- Update
WebhooksModule(src/webhooks/webhooks.module.ts): Import necessary modules.
src/webhooks/webhooks.module.ts:
import { Module, forwardRef } from '@nestjs/common';
import { WebhooksController } from './webhooks.controller';
import { SubscribersModule } from '../subscribers/subscribers.module';
import { MessageBirdModule } from '../messagebird/messagebird.module';
@Module({
imports: [
SubscribersModule,
forwardRef(() => MessageBirdModule),
],
controllers: [WebhooksController],
})
export class WebhooksModule {}
- WebhooksModule is already imported into src/app.module.ts.
3.2 Building the Campaign Sending API
- Create Campaigns Module (
src/campaigns):
nest g module campaigns
nest g controller campaigns --no-spec
nest g service campaigns --no-spec
- Define Campaign DTO (
src/campaigns/dto/create-campaign.dto.ts):
src/campaigns/dto/create-campaign.dto.ts:
import { IsString, IsNotEmpty, MaxLength } from 'class-validator';
export class CreateCampaignDto {
@IsString()
@IsNotEmpty({ message: 'Message content cannot be empty' })
@MaxLength(1600, { message: 'Message is too long (max 1600 characters for multi-part SMS)' })
message: string;
}
- Implement
CampaignsService(src/campaigns/campaigns.service.ts):
src/campaigns/campaigns.service.ts:
import { Injectable, Logger, Inject, forwardRef } from '@nestjs/common';
import { SubscribersService } from '../subscribers/subscribers.service';
import { MessageBirdService } from '../messagebird/messagebird.service';
@Injectable()
export class CampaignsService {
private readonly logger = new Logger(CampaignsService.name);
constructor(
private readonly subscribersService: SubscribersService,
@Inject(forwardRef(() => MessageBirdService))
private readonly messageBirdService: MessageBirdService,
) {}
async sendCampaign(message: string): Promise<{ success: boolean; sentCount: number; failedCount: number; message: string }> {
const shortMessage = message.length > 50 ? `${message.substring(0, 50)}...` : message;
this.logger.log(`Starting campaign send with message: ""${shortMessage}""`);
const activeSubscribers = await this.subscribersService.findActiveSubscribers();
if (!activeSubscribers || activeSubscribers.length === 0) {
this.logger.warn('No active subscribers found. Campaign not sent.');
return { success: false, sentCount: 0, failedCount: 0, message: 'No active subscribers to send to.' };
}
const recipients = activeSubscribers.map(sub => sub.phoneNumber);
this.logger.log(`Attempting to send campaign to ${recipients.length} subscribers.`);
try {
const result = await this.messageBirdService.sendBulkMessage(recipients, message);
const sentCount = result.successCount || recipients.length;
const failedCount = result.failureCount || 0;
if (failedCount > 0) {
this.logger.warn(`Campaign sent with ${failedCount} failures out of ${recipients.length}.`);
return { success: true, sentCount, failedCount, message: `Campaign sent to ${sentCount} subscribers with ${failedCount} failures.` };
} else {
this.logger.log(`Campaign successfully sent to all ${sentCount} subscribers.`);
return { success: true, sentCount, failedCount: 0, message: `Campaign successfully sent to ${sentCount} subscribers.` };
}
} catch (error) {
this.logger.error(`Failed to send campaign: ${error.message}`, error.stack);
return { success: false, sentCount: 0, failedCount: recipients.length, message: `Failed to send campaign due to an error: ${error.message}` };
}
}
}
Simpler Alternative: Send the Same SMS With SMSRoute (No-KYC, Direct Routes)
If you want to replace legacy aggregator SDK boilerplate, multi-week compliance queues, and opaque carrier surcharges with a single HTTP request, SMSRoute delivers global SMS over direct Tier-1 carrier interconnects with instant API access and transparent per-country pricing.
curl -X POST https://api.sendsmsnokyc.com/messages \
-H "x-api-key: $SMSROUTE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"to": ["+14155551234"],
"channel": ["sms"],
"body": "Your verification code is 482910"
}'
- Instant onboarding: No KYC paperwork or sales queues β grab an API key and fund with crypto (BTC/USDT) or card.
- Direct Tier-1 routes: Verify real handset delivery, DLR latency, and Sender ID preservation before launch via SMSRoute Live Carrier Testing.
- Transparent global pricing: Compare exact per-country termination rates on our live pricing page.
Ship Global SMS in One API Call
Skip legacy SDK sprawl and carrier bottlenecks. Send OTPs, alerts, and bulk campaigns across 190+ countries with SMSRoute.
Explore SMSRoute Developers β