Bulk SMS

Build SMS Marketing Campaigns with Twilio, NestJS & Node.js: Complete Guide

Build production-ready SMS marketing campaigns with Twilio API, NestJS, TypeORM, and Bull queues. Includes bulk messaging, subscriber management, webhook handling, and deployment strategies.

JH
Jacky Hossein
β€’ Principal Telecommunications Architect β€’ Published Nov 2, 2026 β€’ 16 min read

Developer Quick-Start: Build production-ready SMS marketing campaigns with Twilio API, NestJS, TypeORM, and Bull queues. Includes bulk messaging, subscriber management, webhook handling, and deployment strategies. 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.

This guide provides a comprehensive, step-by-step walkthrough for building a robust SMS marketing campaign system using Node.js, the NestJS framework, and Twilio's messaging APIs. You'll learn everything from initial project setup to deployment and monitoring, enabling you to send targeted SMS campaigns reliably and efficiently.

You'll create a backend system capable of managing subscribers, defining marketing campaigns, and sending SMS messages in bulk via Twilio, incorporating best practices for scalability, error handling, and security. By the end, you'll have a functional application ready for production use, complete with logging, monitoring, and deployment considerations.

Technologies Used:

  • Node.js: The JavaScript runtime environment.
  • NestJS: A progressive Node.js framework for building efficient, reliable, and scalable server-side applications.
  • Twilio: A cloud communications platform providing APIs for SMS, voice, and more.
  • PostgreSQL: A powerful, open-source object-relational database system.
  • TypeORM: An ORM (Object-Relational Mapper) for TypeScript and JavaScript.
  • Redis: An in-memory data structure store, used here for message queuing.
  • Bull: A robust Redis-based queue system for Node.js.
  • Docker: For containerizing the application for consistent deployment.

System Architecture:

+-------------------+      +---------------------+      +-----------------+      +-----------------+
|   Client / Admin  |----->|   NestJS API Layer  |----->|   Redis (Bull)  |----->|  NestJS Worker  |
| (UI or API Call)  |      | (Controllers, DTOs) |      |   (Message Queue) |      | (Job Processor) |
+-------------------+      +----------+----------+      +--------+--------+      +--------+--------+
                             |          ^                   |                 |
                             |          |                   |                 |
                             v          |                   v                 v
                       +----------+----------+      +-----------------+      +-----------------+
                       |   NestJS Services   |----->| PostgreSQL (DB) |      |   Twilio API    |
                       | (Business Logic)    |      | (Subscribers,   |      | (Send SMS)      |
                       +---------------------+      |  Campaigns)     |      +-----------------+
                                                     +-----------------+

Prerequisites:

  • Node.js (v18 or later recommended) and npm/yarn installed.
  • Access to a PostgreSQL database.
  • A Redis instance (local or cloud-based).
  • A Twilio account with Account SID, Auth Token, and a Twilio phone number.
  • Basic understanding of TypeScript, NestJS, and REST APIs.
  • Docker installed (for deployment section).
  • curl or a tool like Postman for API testing.

1. Setting up the Project

Initialize your NestJS project and install the necessary dependencies.

  1. Create NestJS Project: Use the NestJS CLI to create a new project.
   npm i -g @nestjs/cli
   nest new nestjs-twilio-marketing
   cd nestjs-twilio-marketing
  1. Install Dependencies: You need packages for configuration, Twilio, database interaction (TypeORM, PostgreSQL driver), queuing (Bull), validation, queuing utilities (p-queue, p-retry), and optionally Swagger for API documentation. TypeORM migrations also require ts-node and tsconfig-paths.
   npm install @nestjs/config twilio @nestjs/typeorm typeorm pg @nestjs/bull bull class-validator class-transformer p-queue p-retry

   npm install --save-dev @nestjs/swagger swagger-ui-express ts-node tsconfig-paths
  • @nestjs/config: Handles environment variables.
  • twilio: Official Twilio Node.js helper library.
  • @nestjs/typeorm, typeorm, pg: For PostgreSQL database interaction using TypeORM.
  • @nestjs/bull, bull: For background job processing using Redis.
  • class-validator, class-transformer: For request payload validation.
  • p-queue, p-retry: Utilities for managing concurrency and retries when calling external APIs like Twilio.
  • @nestjs/swagger, swagger-ui-express: For generating API documentation (optional but recommended).
  • ts-node, tsconfig-paths: Required for running TypeORM CLI migrations with TypeScript paths.
  1. Environment Configuration (.env): Create a .env file in your project root. Never commit this file to version control.

.env

   # .env

   # Application
   PORT=3000

   # Database (PostgreSQL)
   DB_HOST=localhost
   DB_PORT=5432
   DB_USERNAME=your_db_user
   DB_PASSWORD=your_db_password
   DB_DATABASE=marketing_db

   # Redis (for Bull Queue)
   REDIS_HOST=localhost
   REDIS_PORT=6379
   # REDIS_PASSWORD=your_redis_password # Uncomment and set if your Redis instance requires a password

   # Twilio Credentials
   TWILIO_ACCOUNT_SID=ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxx # Get from Twilio Console
   TWILIO_AUTH_TOKEN=your_auth_token_xxxxxxxxxxxxxxx # Get from Twilio Console
   TWILIO_PHONE_NUMBER=+15005550006                 # Your Twilio phone number (Test number shown; replace with your actual number for sending)
   TWILIO_STATUS_CALLBACK_URL=http://your_public_domain.com/twilio/status # Needs to be publicly accessible

   # Messaging Service Config
   TWILIO_MESSAGING_SERVICE_SID=MGxxxxxxxxxxxxxxxxxxxxxxxxxxxxx # Optional, but recommended for features like opt-out handling

   # Retry/Queue Config
   TWILIO_SEND_RETRIES=3
   TWILIO_QUEUE_CONCURRENCY=5 # Adjust based on Twilio rate limits and account type
  • Purpose: This file centralizes configuration, keeping secrets out of your codebase.
  • Obtaining Twilio Credentials:
  1. Log in to your Twilio Console.
  2. Your ACCOUNT\_SID and AUTH\_TOKEN are on the main dashboard.
  3. Navigate to Phone Numbers > Manage > Active numbers to find or buy a TWILIO\_PHONE\_NUMBER. Ensure it's SMS-capable. Use the test number +15005550006 for development if needed, but replace it with your actual number for real sending.
  4. (Recommended) Navigate to Messaging > Services > Create Messaging Service. Note the MESSAGING\_SERVICE\_SID. Using a Messaging Service provides advanced features like sender ID pools, geo-matching, and integrated opt-out handling.
  5. The TWILIO\_STATUS\_CALLBACK\_URL is a webhook URL you will create in your NestJS app (Section 4) that Twilio will call to report message status updates (sent, delivered, failed, etc.). It must be publicly accessible. Use tools like ngrok during development.
  • Redis Password: If your Redis instance requires authentication, uncomment the REDIS\_PASSWORD line and provide the correct password.
  1. Load Environment Variables (app.module.ts): Configure the ConfigModule to load the .env file globally.
   import { Module } from '@nestjs/common';
   import { ConfigModule } from '@nestjs/config';
   import { AppController } from './app.controller';
   import { AppService } from './app.service';

   @Module({
     imports: [
       ConfigModule.forRoot({
         isGlobal: true,
         envFilePath: '.env',
       }),

     ],
     controllers: [AppController],
     providers: [AppService],
   })
   export class AppModule {}
  1. Enable Validation Pipe (main.ts): Automatically validate incoming request bodies based on DTOs.
   import { NestFactory } from '@nestjs/core';
   import { AppModule } from './app.module';
   import { ValidationPipe } from '@nestjs/common';
   import { ConfigService } from '@nestjs/config';

   async function bootstrap() {
     const app = await NestFactory.create(AppModule);
     const configService = app.get(ConfigService);

     app.useGlobalPipes(new ValidationPipe({
       whitelist: true,
       transform: true,
       forbidNonWhitelisted: true,
     }));



     const port = configService.get<number>('PORT', 3000);
     await app.listen(port);
     console.log(`Application is running on: ${await app.getUrl()}`);
   }
   bootstrap();
  1. Project Structure (Example): Organize your code into modules for better maintainability.
   src/
   β”œβ”€β”€ app.module.ts
   β”œβ”€β”€ main.ts
   β”œβ”€β”€ config/              # Configuration related files (e.g., TypeORM config)
   β”œβ”€β”€ core/                # Core modules (Auth, Logging, Filters etc. - if needed)
   β”‚   └── filters/
   β”‚       └── http-exception.filter.ts
   β”œβ”€β”€ database/            # Database entities and migrations
   β”‚   β”œβ”€β”€ entities/
   β”‚   β”‚   β”œβ”€β”€ campaign.entity.ts
   β”‚   β”‚   └── subscriber.entity.ts
   β”‚   β”œβ”€β”€ enums/
   β”‚   β”‚   └── campaign-status.enum.ts
   β”‚   └── migrations/
   β”œβ”€β”€ shared/              # Shared modules, services, utilities
   β”‚   └── twilio/          # Twilio integration module
   β”‚       β”œβ”€β”€ twilio.module.ts
   β”‚       └── twilio.service.ts
   β”œβ”€β”€ features/            # Business-logic features
   β”‚   β”œβ”€β”€ campaigns/
   β”‚   β”‚   β”œβ”€β”€ campaigns.module.ts
   β”‚   β”‚   β”œβ”€β”€ campaigns.controller.ts
   β”‚   β”‚   β”œβ”€β”€ campaigns.service.ts
   β”‚   β”‚   └── dtos/
   β”‚   β”‚       └── create-campaign.dto.ts
   β”‚   β”œβ”€β”€ subscribers/
   β”‚   β”‚   β”œβ”€β”€ subscribers.module.ts
   β”‚   β”‚   β”œβ”€β”€ subscribers.controller.ts
   β”‚   β”‚   β”œβ”€β”€ subscribers.service.ts
   β”‚   β”‚   └── dtos/
   β”‚   β”‚       └── add-subscriber.dto.ts
   β”‚   └── messaging/         # Handles queuing and sending logic
   β”‚       β”œβ”€β”€ messaging.module.ts
   β”‚       β”œβ”€β”€ messaging.processor.ts # Bull queue processor
   β”‚       └── messaging.service.ts   # Service to add jobs to the queue
   └── webhooks/            # Controllers handling external webhooks
       └── twilio-status/
           β”œβ”€β”€ twilio-status.controller.ts
           └── twilio-status.module.ts
  • Why this structure? It separates concerns (database, external services, features), making your application easier to understand, test, and scale.

2. Implementing Core Functionality

You'll define database entities, create services for managing campaigns and subscribers, and set up the messaging service.

2.1 Database Schema and Data Layer (TypeORM)

  1. Define Entities: Create TypeORM entities for Campaign and Subscriber.
   import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, UpdateDateColumn, Index } from 'typeorm';

   @Entity('subscribers')
   export class Subscriber {
     @PrimaryGeneratedColumn('uuid')
     id: string;

     @Index({ unique: true })
     @Column({ type: 'varchar', length: 20, unique: true })
     phoneNumber: string;

     @Column({ type: 'varchar', length: 100, nullable: true })
     firstName?: string;

     @Column({ type: 'varchar', length: 100, nullable: true })
     lastName?: string;

     @Column({ type: 'boolean', default: true })
     isOptedIn: boolean;

     @CreateDateColumn()
     createdAt: Date;

     @UpdateDateColumn()
     updatedAt: Date;
   }
   import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, UpdateDateColumn } from 'typeorm';
   import { CampaignStatus } from '../enums/campaign-status.enum';

   @Entity('campaigns')
   export class Campaign {
     @PrimaryGeneratedColumn('uuid')
     id: string;

     @Column({ type: 'varchar', length: 255 })
     name: string;

     @Column({ type: 'text' })
     messageBody: string;



     @Column({
       type: 'enum',
       enum: CampaignStatus,
       default: CampaignStatus.PENDING,
     })
     status: CampaignStatus;

     @Column({ type: 'timestamp', nullable: true })
     scheduledAt?: Date;

     @Column({ type: 'timestamp', nullable: true })
     sentAt?: Date;

     @CreateDateColumn()
     createdAt: Date;

     @UpdateDateColumn()
     updatedAt: Date;


   }

   export enum CampaignStatus {
     PENDING = 'PENDING',
     SENDING = 'SENDING',
     COMPLETED = 'COMPLETED',
     FAILED = 'FAILED',
   }
  1. Configure TypeORM Module: Set up the database connection in app.module.ts using ConfigService.
   import { Module } from '@nestjs/common';
   import { ConfigModule, ConfigService } from '@nestjs/config';
   import { TypeOrmModule } from '@nestjs/typeorm';
   import { AppController } from './app.controller';
   import { AppService } from './app.service';
   import { Campaign } from './database/entities/campaign.entity';
   import { Subscriber } from './database/entities/subscriber.entity';

   @Module({
     imports: [
       ConfigModule.forRoot({ isGlobal: true, envFilePath: '.env' }),
       TypeOrmModule.forRootAsync({
         imports: [ConfigModule],
         inject: [ConfigService],
         useFactory: (configService: ConfigService) => ({
           type: 'postgres',
           host: configService.get<string>('DB_HOST'),
           port: configService.get<number>('DB_PORT'),
           username: configService.get<string>('DB_USERNAME'),
           password: configService.get<string>('DB_PASSWORD'),
           database: configService.get<string>('DB_DATABASE'),
           entities: [Campaign, Subscriber],
           synchronize: false,
           autoLoadEntities: true,
           logging: process.env.NODE_ENV === 'development',
         }),
       }),

     ],
     controllers: [AppController],
     providers: [AppService],
   })
   export class AppModule {}
  1. Database Migrations: TypeORM CLI is needed for migrations. Add scripts to package.json. Ensure ts-node and tsconfig-paths are installed (done in Step 1).
   "scripts": {

     "typeorm": "ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js --dataSource src/config/typeorm.config.ts",
     "migration:generate": "npm run typeorm -- migration:generate",
     "migration:run": "npm run typeorm -- migration:run",
     "migration:revert": "npm run typeorm -- migration:revert"
   },

Create a TypeORM configuration file for the CLI:

   import { DataSource, DataSourceOptions } from 'typeorm';
   import { ConfigModule, ConfigService } from '@nestjs/config';
   import { Campaign } from '../database/entities/campaign.entity';
   import { Subscriber } from '../database/entities/subscriber.entity';

   import * as dotenv from 'dotenv';
   dotenv.config();

   const configService = new ConfigService();

   export const dataSourceOptions: DataSourceOptions = {
       type: 'postgres',
       host: configService.get<string>('DB_HOST'),
       port: configService.get<number>('DB_PORT'),
       username: configService.get<string>('DB_USERNAME'),
       password: configService.get<string>('DB_PASSWORD'),
       database: configService.get<string>('DB_DATABASE'),
       entities: [Campaign, Subscriber],
       migrations: [__dirname + '/../database/migrations/*{.ts,.js}'],
       synchronize: false,
       logging: true,
   };

   const dataSource = new DataSource(dataSourceOptions);
   export default dataSource;

Now you can generate and run migrations:

  • Make changes to your entities.
  • Generate a migration: npm run migration:generate src/database/migrations/MyFeatureMigration (replace MyFeatureMigration with a descriptive name).
  • Review the generated SQL in the migration file.
  • Run the migration: npm run migration:run

2.2 Feature Modules (Campaigns, Subscribers)

Create modules, controllers, services, and DTOs for managing campaigns and subscribers.

Campaigns Feature:

  1. DTO (CreateCampaignDto):
   import { IsString, IsNotEmpty, MaxLength } from 'class-validator';

   export class CreateCampaignDto {
     @IsString()
     @IsNotEmpty()
     @MaxLength(255)
     name: string;

     @IsString()
     @IsNotEmpty()
     messageBody: string;


   }
  1. Service (CampaignsService):
   import { Injectable, NotFoundException, Logger } from '@nestjs/common';
   import { InjectRepository } from '@nestjs/typeorm';
   import { Repository } from 'typeorm';
   import { Campaign } from '../../database/entities/campaign.entity';
   import { CreateCampaignDto } from './dtos/create-campaign.dto';
   import { CampaignStatus } from '../../database/enums/campaign-status.enum';
   import { MessagingService } from '../messaging/messaging.service';

   @Injectable()
   export class CampaignsService {
     private readonly logger = new Logger(CampaignsService.name);

     constructor(
       @InjectRepository(Campaign)
       private campaignsRepository: Repository<Campaign>,

       private readonly messagingService: MessagingService,
     ) {}

     async create(createCampaignDto: CreateCampaignDto): Promise<Campaign> {
       const campaign = this.campaignsRepository.create({
           ...createCampaignDto,
           status: CampaignStatus.PENDING,
       });
       return this.campaignsRepository.save(campaign);
     }

     async findAll(): Promise<Campaign[]> {
       return this.campaignsRepository.find();
     }

     async findOne(id: string): Promise<Campaign> {
       const campaign = await this.campaignsRepository.findOneBy({ id });
       if (!campaign) {
         throw new NotFoundException(`Campaign with ID ${id} not found`);
       }
       return campaign;
     }

     async startCampaign(id: string): Promise<{ message: string; queuedMessages: number }> {
       const campaign = await this.findOne(id);
       if (campaign.status !== CampaignStatus.PENDING) {

         throw new Error(`Campaign ${id} is not in PENDING state (current: ${campaign.status}).`);
       }


       await this.campaignsRepository.update(id, { status: CampaignStatus.SENDING, sentAt: new Date() });
       this.logger.log(`Campaign ${id} status updated to SENDING.`);


       const queuedCount = await this.messagingService.queueCampaignMessages(campaign);
       this.logger.log(`Queued ${queuedCount} messages for campaign ${id}.`);

       return { message: `Campaign ${id} sending process initiated.`, queuedMessages: queuedCount };
     }


   }
  1. Controller (CampaignsController):
   import { Controller, Get, Post, Body, Param, ParseUUIDPipe, HttpCode, HttpStatus } from '@nestjs/common';
   import { CampaignsService } from './campaigns.service';
   import { CreateCampaignDto } from './dtos/create-campaign.dto';
   import { Campaign } from '../../database/entities/campaign.entity';

   @Controller('campaigns')
   export class CampaignsController {
     constructor(private readonly campaignsService: CampaignsService) {}



     @Post()
     @HttpCode(HttpStatus.CREATED)
     create(@Body() createCampaignDto: CreateCampaignDto): Promise<Campaign> {
       return this.campaignsService.create(createCampaignDto);
     }



     @Get()
     findAll(): Promise<Campaign[]> {
       return this.campaignsService.findAll();
     }




     @Get(':id')
     findOne(@Param('id', ParseUUIDPipe) id: string): Promise<Campaign> {
       return this.campaignsService.findOne(id);
     }






     @Post(':id/send')
     @HttpCode(HttpStatus.ACCEPTED)
     startSending(@Param('id', ParseUUIDPipe) id: string): Promise<{ message: string; queuedMessages: number }> {

       return this.campaignsService.startCampaign(id);
     }
   }
  1. Module (CampaignsModule):
   import { Module } from '@nestjs/common';
   import { TypeOrmModule } from '@nestjs/typeorm';
   import { CampaignsService } from './campaigns.service';
   import { CampaignsController } from './campaigns.controller';
   import { Campaign } from '../../database/entities/campaign.entity';
   import { MessagingModule } from '../messaging/messaging.module';

   @Module({
     imports: [
       TypeOrmModule.forFeature([Campaign]),
       MessagingModule,
     ],
     controllers: [CampaignsController],
     providers: [CampaignsService],
   })
   export class CampaignsModule {}

Subscribers Feature: Implement similarly (DTO, Service, Controller, Module) for adding, listing, updating (opt-out status), and deleting subscribers. Ensure you validate phone numbers and store them in E.164 format.

import { IsString, IsNotEmpty, IsPhoneNumber, IsOptional, IsBoolean } from 'class-validator';

export class AddSubscriberDto {
  @IsPhoneNumber(null)
  @IsNotEmpty()
  phoneNumber: string;

  @IsString()
  @IsOptional()
  firstName?: string;

  @IsString()
  @IsOptional()
  lastName?: string;

  @IsBoolean()
  @IsOptional()
  isOptedIn?: boolean = true;
}

(Note: Service, Controller, and Module for Subscribers are omitted for brevity but should follow the same pattern as Campaigns.)

Finally, import CampaignsModule and SubscribersModule (once created) into AppModule.

3. Building the API Layer

You've already started building the API layer with controllers and DTOs.

  • Authentication/Authorization: For production, protect your endpoints. Use NestJS Guards with strategies like JWT (@nestjs/jwt, @nestjs/passport). Apply guards to controllers or specific routes (@UseGuards(AuthGuard('jwt'))). This is beyond the scope of this basic guide but crucial for security.
  • Request Validation: Handled by ValidationPipe configured in main.ts and class-validator decorators in DTOs.
  • API Documentation (Swagger – Optional):
  1. Install dev dependencies (done in Step 1).
  2. Setup in main.ts:
     import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';

     async function bootstrap() {
       const app = await NestFactory.create(AppModule);
       const configService = app.get(ConfigService);

       app.useGlobalPipes(new ValidationPipe({
          whitelist: true,
          transform: true,
          forbidNonWhitelisted: true,
        }));


       const swaggerConfig = new DocumentBuilder()
         .setTitle('Marketing Campaign API')
         .setDescription('API for managing SMS marketing campaigns and subscribers')
         .setVersion('1.0')
         .addBearerAuth()
         .build();
       const document = SwaggerModule.createDocument(app, swaggerConfig);
       SwaggerModule.setup('api-docs', app, document);

       const port = configService.get<number>('PORT', 3000);
       await app.listen(port);
       console.log(`Application is running on: ${await app.getUrl()}`);
       console.log(`API documentation available at ${await app.getUrl()}/api-docs`);
     }
     bootstrap();
  1. Decorate controllers and DTOs with @ApiTags, @ApiOperation, @ApiResponse, @ApiProperty, etc. as needed (examples shown commented out in CampaignsController).
  • Testing Endpoints (curl examples):
  • Create Campaign:
    curl -X POST http://localhost:3000/campaigns \
         -H "Content-Type: application/json" \
         -d '{
               "name": "Spring Sale 2025",
               "messageBody": "Huge Spring Sale starts now! Visit example.com/sale. Reply STOP to opt out."
             }'

(Response: JSON object of the created campaign)

  • Add Subscriber:
    curl -X POST http://localhost:3000/subscribers \
         -H "Content-Type: application/json" \
         -d '{
               "phoneNumber": "+14155551234",
               "firstName": "Jane",
               "lastName": "Doe"
             }'

(Response: JSON object of the added subscriber)

  • Start Sending Campaign:
    curl -X POST http://localhost:3000/campaigns/<campaign-uuid>/send

(Response: { "message": "Campaign <campaign-uuid> sending process initiated.", "queuedMessages": X })

4. Integrating with Twilio

Create a dedicated module for Twilio interactions and handle status callbacks.

  1. Twilio Service (TwilioService): This service initializes the Twilio client and provides methods to send SMS. You'll incorporate p-queue for concurrency control and p-retry for robustness.
   import PQueue from 'p-queue';
   import pRetry from 'p-retry';
   import twilio, { Twilio } from 'twilio';
   import { Injectable, Logger, OnModuleInit } from '@nestjs/common';
   import { ConfigService } from '@nestjs/config';
   import { MessageListInstanceCreateOptions } from 'twilio/lib/rest/api/v2010/account/message';
   import { Request } from 'express';

   @Injectable()
   export class TwilioService implements OnModuleInit {
     private client: Twilio;
     private readonly logger = new Logger(TwilioService.name);
     private queue: PQueue;
     private messagingServiceSid: string | undefined;
     private twilioPhoneNumber: string | undefined;
     private statusCallbackUrl: string | undefined;
     private authToken: string | undefined;

     constructor(private configService: ConfigService) {}

     onModuleInit() {
       const accountSid = this.configService.get<string>('TWILIO_ACCOUNT_SID');
       this.authToken = this.configService.get<string>('TWILIO_AUTH_TOKEN');
       const concurrency = this.configService.get<number>('TWILIO_QUEUE_CONCURRENCY', 5);
       this.messagingServiceSid = this.configService.get<string>('TWILIO_MESSAGING_SERVICE_SID');
       this.twilioPhoneNumber = this.configService.get<string>('TWILIO_PHONE_NUMBER');
       this.statusCallbackUrl = this.configService.get<string>('TWILIO_STATUS_CALLBACK_URL');

       if (!accountSid || !this.authToken) {
         this.logger.error('Twilio Account SID or Auth Token missing in config.');
         throw new Error('Twilio credentials not found. SMS sending disabled.');
       }

       if (!this.messagingServiceSid && !this.twilioPhoneNumber) {
            this.logger.error('Either TWILIO_MESSAGING_SERVICE_SID or TWILIO_PHONE_NUMBER must be configured.');
            throw new Error('Twilio sender identifier not found.');
       }

       this.client = twilio(accountSid, this.authToken);
       this.queue = new PQueue({ concurrency });
       this.logger.log('Twilio Client Initialized.');
       if(this.messagingServiceSid) {
           this.logger.log(`Using Messaging Service SID: ${this.messagingServiceSid}`);
       } else {
           this.logger.log(`Using Twilio Phone Number: ${this.twilioPhoneNumber}`);
       }
     }

     private async sendSmsInternal(options: MessageListInstanceCreateOptions): Promise<any> {

       const sender = this.messagingServiceSid
         ? { messagingServiceSid: this.messagingServiceSid }
         : { from: this.twilioPhoneNumber };

       const payload: MessageListInstanceCreateOptions = {
           ...options,
           ...sender,
           statusCallback: this.statusCallbackUrl,
       };

       this.logger.debug(`Sending SMS via Twilio: ${JSON.stringify({...payload, body: '[REDACTED]'})}`);
       return this.client.messages.create(payload);
     }


     async queueSms(options: Pick<MessageListInstanceCreateOptions, 'to' | 'body'>) {
       const retries = this.configService.get<number>('TWILIO_SEND_RETRIES', 3);

       return this.queue.add(() =>
         pRetry(() => this.sendSmsInternal(options), {
           onFailedAttempt: (error) => {
             this.logger.warn(
               `SMS to ${options.to} failed. Retrying (${error.retriesLeft} attempts left). Error: ${error.message}`,
                error.name === 'TwilioRestException' ? error.cause : error.stack,
             );
           },
           retries: retries,
         }),
       );
     }


   }
  1. Twilio Module (TwilioModule):
   import { Module, Global } from '@nestjs/common';
   import { ConfigModule } from '@nestjs/config';
   import { TwilioService } from './twilio.service';

   @Global()
   @Module({
     imports: [ConfigModule],
     providers: [TwilioService],
     exports: [TwilioService],
   })
   export class TwilioModule {}
  1. Import TwilioModule into AppModule:
   import { TwilioModule } from './shared/twilio/twilio.module';

   @Module({
     imports: [

       TwilioModule,

     ],

   })
   export class AppModule {}
  1. Status Callback Controller (TwilioStatusController): Create a controller to handle incoming webhook requests from Twilio about message status updates. Crucially, secure this endpoint.
   import { Controller, Post, Body, Req, Res, Logger, ForbiddenException, Headers } from '@nestjs/common';
   import { Request, Response } from 'express';
   import { validateRequest } from 'twilio';
   import { ConfigService } from '@nestjs/config';

   @Controller('twilio/status')
   export class TwilioStatusController {
     private readonly logger = new Logger(TwilioStatusController.name);
     private twilioAuthToken: string;

     constructor(private configService: ConfigService) {
       this.twilioAuthToken = this.configService.get<string>('TWILIO_AUTH_TOKEN');
       if (!this.twilioAuthToken) {
         this.logger.error('TWILIO_AUTH_TOKEN not configured. Webhook validation disabled!');

       }
     }

     @Post()
     handleStatusUpdate(
       @Headers('X-Twilio-Signature') twilioSignature: string,
       @Body() body: any,
       @Req() req: Request,
       @Res() res: Response,
     ) {
       this.logger.debug(`Received Twilio status update: ${JSON.stringify(body)}`);


       const url = this.configService.get<string>('TWILIO_STATUS_CALLBACK_URL');
       if (!this.twilioAuthToken || !url) {
          this.logger.error('Cannot validate Twilio request: Auth Token or Callback URL missing.');
          throw new ForbiddenException('Webhook validation configuration missing.');
       }








       const isValid = validateRequest(this.twilioAuthToken, twilioSignature, url, body);

       if (!isValid) {
         this.logger.warn('Invalid Twilio signature received.');
         throw new ForbiddenException('Invalid Twilio signature.');
       }


       const messageSid = body.MessageSid;
       const messageStatus = body.MessageStatus;
       const errorCode = body.ErrorCode;
       const to = body.To;

       this.logger.log(`Message ${messageSid} to ${to} status: ${messageStatus}${errorCode ? ` (Error: ${errorCode})` : ''}`);







       res.status(204).send();
     }
   }
  1. Status Callback Module (TwilioStatusModule):
   import { Module } from '@nestjs/common';
   import { ConfigModule } from '@nestjs/config';
   import { TwilioStatusController } from './twilio-status.controller';

   @Module({
     imports: [ConfigModule],
     controllers: [TwilioStatusController],
   })
   export class TwilioStatusModule {}
  1. Import TwilioStatusModule into AppModule:
   import { TwilioStatusModule } from './webhooks/twilio-status/twilio-status.module';

   @Module({
     imports: [

       TwilioStatusModule,
     ],

   })
   export class AppModule {}

Important Notes on Webhook Validation:

  • The validateRequest function from twilio requires the original URL Twilio called and the raw, unparsed POST body parameters.
  • Standard NestJS body parsing might interfere. You may need specific middleware for the /twilio/status route to capture the raw body before it's parsed, or carefully reconstruct the parameters as Twilio sent them (which is less secure). Research NestJS raw body handling for robust validation.
  • Ensure your TWILIO\_STATUS\_CALLBACK\_URL in .env exactly matches the public URL configured in Twilio and used in the validation. Use ngrok or similar tools for local development to get a public URL.

Frequently Asked Questions (FAQ)

What Node.js version should I use for this Twilio NestJS marketing campaign system?

Use Node.js v18 or later (v20 LTS recommended) as specified in the prerequisites. Node.js 18.x provides long-term support and is compatible with NestJS, Twilio SDK, TypeORM, and Bull queue dependencies used in this guide.

Do I need a paid Twilio account to send marketing SMS campaigns?

Yes. While Twilio offers trial accounts for testing, production SMS marketing campaigns require a paid account with purchased phone numbers or a Messaging Service SID. Trial accounts have limitations on recipient numbers (only verified numbers) and sending volumes. Review Twilio's pricing and upgrade your account before launching campaigns.

How do I prevent sending duplicate SMS messages to the same subscriber?

Use Bull queue's built-in job deduplication by setting a unique jobId based on campaign ID and subscriber phone number combination. Additionally, track message sends in your database with a compound index on (campaignId, subscriberId) and check before queuing. The guide's architecture with PostgreSQL and TypeORM supports adding a MessageLog entity for tracking.

Start with TWILIO_QUEUE_CONCURRENCY=5 as shown in the .env configuration. Twilio's default rate limit is typically 1 message per second for trial accounts and higher for paid accounts (varies by account type). Monitor your specific account limits in the Twilio Console and adjust the p-queue concurrency setting accordingly to avoid rate limit errors (HTTP 429).

How do I handle Twilio SMS delivery failures and retries?

The guide implements retry logic using p-retry in TwilioService.queueSms() with configurable TWILIO_SEND_RETRIES (default 3 attempts). For delivery status tracking, implement the TwilioStatusController webhook to receive status updates ("delivered", "failed", "undelivered"). Store Twilio's MessageSid when sending, then match it in the webhook to update your database and trigger retry logic for failed messages.

Can I use this system with Twilio Messaging Services instead of phone numbers?

Yes. The code supports both approaches. Set TWILIO_MESSAGING_SERVICE_SID in your .env file to use a Messaging Service (recommended for features like sender ID pools, geo-matching, and integrated opt-out handling). If not set, the system falls back to TWILIO_PHONE_NUMBER. The TwilioService automatically selects the appropriate sender identifier.

How do I deploy this NestJS Twilio marketing system to production?

Use Docker containerization (as referenced in prerequisites) with a multi-stage Dockerfile. Deploy to platforms like AWS ECS, Google Cloud Run, Azure Container Instances, or DigitalOcean App Platform. Ensure PostgreSQL and Redis are accessible (use managed services like AWS RDS and ElastiCache). Set all environment variables in your deployment platform, configure webhook URLs to your public domain, and implement proper monitoring with tools like DataDog, New Relic, or AWS CloudWatch.

What database migrations strategy should I use for production?

Use TypeORM migrations as demonstrated in the guide. Set synchronize: false in production TypeOrmModule configuration. Generate migrations with npm run migration:generate after entity changes, review the generated SQL, and run npm run migration:run during deployment. Store migrations in version control and automate migration execution in your CI/CD pipeline before starting the application.


Official Documentation

  • Twilio SMS API Documentation – Complete reference for Twilio's Programmable SMS API, including rate limits, best practices, and advanced features
  • NestJS Official Documentation – Comprehensive guides for building scalable Node.js applications with NestJS framework architecture
  • TypeORM Documentation – Database ORM documentation covering entities, migrations, and advanced query techniques
  • Bull Queue Documentation – Redis-based queue system for Node.js with detailed examples for job processing and concurrency control

SMS Marketing Best Practices

  • CTIA Messaging Principles and Best Practices – Industry standards for compliant SMS marketing campaigns in the United States
  • Twilio's Guide to A2P 10DLC – Understanding Application-to-Person messaging registration requirements for US long code SMS campaigns

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 β†’