Developer Quick-Start: A guide on setting up a NestJS application to send and receive WhatsApp messages via the MessageBird Conversations API, including project setup, sending messages, and handling webhooks. 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.
Build a production-ready WhatsApp Business API integration for your Node.js application using NestJS and the MessageBird Conversations API. This complete tutorial covers project setup, webhook handling, sending messages (text and media), implementing secure authentication, and adapting to 2025 WhatsApp Business API changes.
Important Note (2025): MessageBird rebranded to Bird.com in February 2024. However, the
legacy APIs, SDKs (including the Node.js messagebird package), and developer documentation still
use the MessageBird branding. This guide uses "MessageBird" when referring to the SDK and APIs, but the
company now operates as Bird.com.
By completing this NestJS WhatsApp integration tutorial, you'll have a functional application that sends and receives WhatsApp messages programmatically β perfect for building chatbots, automated notification systems, or customer support tools. You'll need basic familiarity with Node.js, TypeScript, and NestJS concepts.
What You'll Build with This WhatsApp API Integration
Create a NestJS backend service that:
- Exposes an API endpoint to send outbound WhatsApp messages (text and media)
- Receives inbound WhatsApp messages and status updates via MessageBird webhooks
- Securely handles API keys and webhook requests
- (Optional) Persists message history in a database
Why This Matters:
Leverage WhatsApp's ubiquity to communicate with users in their preferred messaging app. Automate interactions, send timely notifications, and provide support without requiring users to install a separate application.
Technologies:
- Node.js: JavaScript runtime environment
- NestJS: Progressive Node.js framework for building efficient, scalable server-side applications with TypeScript. Features modular architecture, dependency injection, and built-in validation and configuration support
- TypeScript: JavaScript superset adding static types for improved code quality and maintainability
- MessageBird (now Bird.com): Cloud communications platform with APIs for multiple channels, including WhatsApp. You'll use their official Node.js SDK and Conversations API
- MessageBird WhatsApp Sandbox: Development environment for testing WhatsApp integration without a fully approved WhatsApp Business Account
- (Optional) Prisma: Next-generation ORM for Node.js and TypeScript, used for database interaction if you need message persistence
- (Optional) PostgreSQL/SQLite: Relational database for storing message data
System Architecture:
(A sequence diagram illustrating the flow between Client, NestJS App, MessageBird API, and WhatsApp was intended here.)
Prerequisites:
- Node.js LTS version (v18.x, v20.x, or v22.x as of 2025) and npm/yarn. Note: NestJS 10 and 11 require Node.js v16 or higher
- MessageBird Account (sign up at https://messagebird.com/ or https://bird.com/)
- Access to the MessageBird WhatsApp Sandbox OR a provisioned WhatsApp Business channel
- API testing tool (Postman or curl)
- (Optional) Database instance (e.g., PostgreSQL) for persistence
- (Optional) ngrok or similar tool to expose your local development server for webhook testing
SDK Version Notice: The messagebird npm package (v4.0.1) was last updated
approximately 3 years ago (as of 2025). While functional for basic use cases, it may not receive regular
updates or support for newer WhatsApp Business API features. Monitor the official Bird.com developer
documentation for migration paths or new SDK releases.
1. Setting Up Your NestJS WhatsApp Project
Initialize your NestJS project and install the required dependencies for WhatsApp API integration.
Install NestJS CLI:
If you haven't installed it globally:
npm install -g @nestjs/cli
yarn global add @nestjs/cli
Create Your NestJS Project:
nest new nestjs-whatsapp-messagebird
cd nestjs-whatsapp-messagebird
Choose your preferred package manager (npm or yarn) when prompted.
Install Required Dependencies:
Install the MessageBird SDK and NestJS configuration module:
npm install messagebird @nestjs/config class-validator class-transformer
yarn add messagebird @nestjs/config class-validator class-transformer
- messagebird: Official Node.js SDK for the MessageBird API
- @nestjs/config: Securely manages environment variables
- class-validator & class-transformer: Validate incoming request data (DTOs)
Configure Environment Variables:
Create a .env file in your project root to store sensitive credentials. Never commit
this file to version control. Ensure .env is in your .gitignore.
.env
# .env
# MessageBird Credentials
MESSAGEBIRD_API_KEY=YOUR_MESSAGEBIRD_LIVE_OR_TEST_API_KEY
MESSAGEBIRD_WHATSAPP_CHANNEL_ID=YOUR_WHATSAPP_CHANNEL_ID_FROM_MESSAGEBIRD
# Webhook Security
MESSAGEBIRD_WEBHOOK_SIGNING_KEY=YOUR_GENERATED_WEBHOOK_SIGNING_KEY
WEBHOOK_BASE_URL=http://localhost:3000 # Replace with ngrok URL or deployed URL
Obtain Your MessageBird API Credentials:
MESSAGEBIRD_API_KEY:
- Log in to your MessageBird Dashboard (accessible via https://dashboard.messagebird.com/ or through Bird.com)
- Navigate to Developers > API access
- Click "Add access key." Choose "Live" or "Test" mode. Copy the generated key. Note: Test keys work with the Sandbox but won't send real messages
MESSAGEBIRD_WHATSAPP_CHANNEL_ID:
- Navigate to Channels > WhatsApp
- For Sandbox: Find the "WhatsApp Sandbox" entry. The Channel ID is listed there
- For provisioned channel: Find your channel name. The Channel ID is listed there
MESSAGEBIRD_WEBHOOK_SIGNING_KEY:
- Navigate to Developers > Webhook Signing
- Click "Generate new signing key." Copy the generated key
WEBHOOK_BASE_URL: Set the public URL where MessageBird sends webhook events. For local development, usengrok:
- Install ngrok: https://ngrok.com/download
- Run: ngrok http 3000 (assuming your NestJS app runs on port 3000)
- Copy the https forwarding URL from ngrok (e.g., https://abcdef123456.ngrok.io). Use this as your base URL
- Important: Update the webhook configuration in MessageBird whenever your ngrok URL changes. Ngrok provides temporary URLs for local development and testing only. For staging or production, use a stable, publicly accessible HTTPS endpoint on your server
Load Environment Variables:
Import and configure ConfigModule in your main application module
(src/app.module.ts) to make environment variables accessible throughout your application.
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 {}
Project Structure:
We'll organize our code into modules for better separation of concerns:
src/
βββ app.controller.ts
βββ app.module.ts
βββ app.service.ts
βββ main.ts
βββ config/ # Configuration related files (if needed beyond .env)
βββ core/ # Core services like MessageBird client wrapper, Prisma
β βββ messagebird/
β β βββ messagebird.module.ts
β β βββ messagebird.service.ts
β βββ prisma/ # (Optional) If using Prisma
β βββ prisma.module.ts
β βββ prisma.service.ts
βββ modules/ # Feature modules
β βββ whatsapp/
β β βββ dto/
β β β βββ send-whatsapp-message.dto.ts
β β βββ whatsapp.controller.ts
β β βββ whatsapp.module.ts
β β βββ whatsapp.service.ts
β βββ webhooks/
β βββ dto/
β β βββ messagebird-webhook.dto.ts # Defines expected payload structure
β βββ webhooks.controller.ts
β βββ webhooks.module.ts
βββ common/ # Shared utilities, decorators, middleware etc.
β βββ middleware/
β βββ messagebird-verify.middleware.ts # For signature verification
prisma/ # (Optional) Prisma schema and migrations
βββ schema.prisma
# ... other configuration files (.env, .gitignore, tsconfig.json, etc.)
This structure promotes modularity and makes the application easier to maintain and scale.
2. Configure the MessageBird Client Service
Let's create a dedicated service to initialize and provide the MessageBird client instance.
1. Create the Module and Service:
nest generate module core/messagebird --flat
nest generate service core/messagebird --flat
2. Implement the Service:
This service will inject NestJS's ConfigService to retrieve the API key and initialize the
messagebird client.
import { Injectable, OnModuleInit, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import * as MessageBird from 'messagebird';
@Injectable()
export class MessageBirdService implements OnModuleInit {
private readonly logger = new Logger(MessageBirdService.name);
private client: MessageBird.MessageBird;
constructor(private configService: ConfigService) {}
onModuleInit() {
const apiKey = this.configService.get<string>('MESSAGEBIRD_API_KEY');
if (!apiKey) {
this.logger.error('MESSAGEBIRD_API_KEY is not defined in environment variables.');
throw new Error('MessageBird API Key is required.');
}
this.client = MessageBird(apiKey);
this.logger.log('MessageBird client initialized successfully.');
}
getClient(): MessageBird.MessageBird {
if (!this.client) {
this.logger.error('MessageBird client requested before initialization.');
throw new Error('MessageBird client not initialized.');
}
return this.client;
}
}
3. Create the Module:
Export the MessageBirdService so other modules can use it.
import { Module, Global } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { MessageBirdService } from './messagebird.service';
@Global()
@Module({
imports: [ConfigModule],
providers: [MessageBirdService],
exports: [MessageBirdService],
})
export class MessageBirdModule {}
4. Import MessageBirdModule in AppModule:
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { MessageBirdModule } from './core/messagebird/messagebird.module';
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
envFilePath: '.env',
}),
MessageBirdModule,
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
Now, the MessageBirdService can be injected into any other service or controller in our
application.
3. How to Send WhatsApp Messages with NestJS
We'll create a dedicated module (WhatsappModule) with a controller and service to handle
sending WhatsApp messages.
1. Create Module, Controller, Service, and DTO:
nest generate module modules/whatsapp
nest generate controller modules/whatsapp
nest generate service modules/whatsapp
mkdir -p src/modules/whatsapp/dto
touch src/modules/whatsapp/dto/send-whatsapp-message.dto.ts
2. Define the Request DTO:
Create a Data Transfer Object (DTO) to define the expected structure and validation rules for the request body when sending a message.
import { IsNotEmpty, IsString, IsPhoneNumber, IsOptional, IsUrl } from 'class-validator';
export class SendWhatsappMessageDto {
@IsNotEmpty()
@IsPhoneNumber(null)
@IsString()
readonly to: string;
@IsNotEmpty()
@IsString()
readonly text: string;
@IsOptional()
@IsUrl()
readonly imageUrl?: string;
@IsOptional()
@IsUrl()
readonly videoUrl?: string;
@IsOptional()
@IsUrl()
readonly audioUrl?: string;
@IsOptional()
@IsUrl()
readonly fileUrl?: string;
@IsOptional()
@IsString()
readonly caption?: string;
}
3. Implement the WhatsApp Service:
Inject MessageBirdService and ConfigService to interact with the API.
Note: The specific types imported from messagebird/types/conversations can change between
SDK versions. Ensure these types are compatible with your installed messagebird package
version.
import { Injectable, Logger, HttpException, HttpStatus } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { MessageBirdService } from '../../core/messagebird/messagebird.service';
import { SendWhatsappMessageDto } from './dto/send-whatsapp-message.dto';
import {
StartConversationParameter,
Content,
TextContent,
ImageContent,
VideoContent,
AudioContent,
FileContent,
} from 'messagebird/types/conversations';
@Injectable()
export class WhatsappService {
private readonly logger = new Logger(WhatsappService.name);
private readonly channelId: string;
constructor(
private readonly messageBirdService: MessageBirdService,
private readonly configService: ConfigService,
) {
this.channelId = this.configService.get<string>('MESSAGEBIRD_WHATSAPP_CHANNEL_ID');
if (!this.channelId) {
this.logger.error('MESSAGEBIRD_WHATSAPP_CHANNEL_ID is not defined.');
throw new Error('WhatsApp Channel ID is required.');
}
}
async sendMessage(dto: SendWhatsappMessageDto): Promise<any> {
const client = this.messageBirdService.getClient();
let content: Content;
if (dto.imageUrl) {
content = { image: { url: dto.imageUrl, caption: dto.caption } } as ImageContent;
} else if (dto.videoUrl) {
content = { video: { url: dto.videoUrl, caption: dto.caption } } as VideoContent;
} else if (dto.audioUrl) {
content = { audio: { url: dto.audioUrl } } as AudioContent;
} else if (dto.fileUrl) {
content = { file: { url: dto.fileUrl, caption: dto.caption } } as FileContent;
} else {
content = { text: dto.text } as TextContent;
}
const params: StartConversationParameter = {
to: dto.to,
channelId: this.channelId,
type: this.getContentType(content),
content: content,
};
this.logger.log(`Attempting to send message via channel ${this.channelId} to ${dto.to}. Payload: ${JSON.stringify(params)}`);
try {
const result = await client.conversations.start(params);
this.logger.log(`Message accepted by MessageBird. ConversationID: ${result.id}, MessageID: ${result.messages?.lastMessageId}`);
return result;
} catch (error) {
const statusCode = error.response?.status || HttpStatus.INTERNAL_SERVER_ERROR;
const errorData = error.response?.data || error.message;
this.logger.error(`MessageBird API Error (${statusCode}) for recipient ${dto.to}: ${JSON.stringify(errorData)}`, error.stack);
if (statusCode === 400 || statusCode === 422) {
throw new HttpException({
message: 'Failed to send message due to invalid data or number.',
details: errorData
}, HttpStatus.BAD_REQUEST);
}
throw new HttpException('Failed to send WhatsApp message.', HttpStatus.INTERNAL_SERVER_ERROR);
}
}
private getContentType(content: Content): string {
if ('text' in content) return 'text';
if ('image' in content) return 'image';
if ('video' in content) return 'video';
if ('audio' in content) return 'audio';
if ('file' in content) return 'file';
return 'text';
}
}
- Why
conversations.start? This API call is versatile. It can initiate a new conversation (if one doesn't exist or is archived) or send a message to an existing active conversation. For initiating conversations outside WhatsApp's 24-hour window, you'll need HSM templates. conversations.reply requires an existing conversationId.
4. Implement the WhatsApp Controller:
Expose a POST endpoint to trigger the sendMessage service method. Use
ValidationPipe to automatically validate incoming DTOs.
import { Controller, Post, Body, UsePipes, ValidationPipe, HttpCode, HttpStatus } from '@nestjs/common';
import { WhatsappService } from './whatsapp.service';
import { SendWhatsappMessageDto } from './dto/send-whatsapp-message.dto';
@Controller('whatsapp')
export class WhatsappController {
constructor(private readonly whatsappService: WhatsappService) {}
@Post('send')
@UsePipes(new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true }))
@HttpCode(HttpStatus.ACCEPTED)
async sendMessage(@Body() sendWhatsappMessageDto: SendWhatsappMessageDto) {
try {
const result = await this.whatsappService.sendMessage(sendWhatsappMessageDto);
return {
message: 'Message accepted for delivery.',
details: {
conversationId: result.id,
messageId: result.messages?.lastMessageId
}
};
} catch (error) {
throw error;
}
}
}
5. Register WhatsappModule in AppModule:
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { MessageBirdModule } from './core/messagebird/messagebird.module';
import { WhatsappModule } from './modules/whatsapp/whatsapp.module';
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
envFilePath: '.env',
}),
MessageBirdModule,
WhatsappModule,
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
6. Testing the WhatsApp API Endpoint:
Start your NestJS application:
npm run start:dev
yarn start:dev
Use curl or Postman to send a request to POST http://localhost:3000/whatsapp/send
(replace port if needed).
Example curl (Text Message):
Remember to use a number registered with your WhatsApp Sandbox for testing initially.
curl -X POST http://localhost:3000/whatsapp/send \
-H "Content-Type: application/json" \
-d '{
"to": "+12345678900",
"text": "Hello from NestJS and MessageBird!"
}'
Example curl (Image Message):
curl -X POST http://localhost:3000/whatsapp/send \
-H "Content-Type: application/json" \
-d '{
"to": "+12345678900",
"text": "Check out this logo",
"imageUrl": "https://www.messagebird.com/assets/images/og/messagebird.png",
"caption": "MessageBird Logo"
}'
Expected Response (Success - 202 Accepted):
{
"message": "Message accepted for delivery.",
"details": {
"conversationId": "conv_id_from_messagebird_xxxxxxxx",
"messageId": "msg_id_from_messagebird_yyyyyyyy"
}
}
You should receive the WhatsApp message on the target device shortly after. Check your application logs for
details from WhatsappService.
4. Receiving WhatsApp Messages via Webhooks
MessageBird uses webhooks to notify your application about incoming messages
(message.created) and status updates for outgoing messages (message.updated).
1. Configure Webhook in MessageBird Dashboard:
- Go to your MessageBird Dashboard > Channels > WhatsApp > Select your Channel (e.g., Sandbox).
- Find the 'Webhooks' or 'Conversation Webhooks' section.
- Click 'Add webhook'.
- URL: Enter your public webhook URL. Using the .env variable: ${WEBHOOK\_BASE\_URL}/webhooks/messagebird. For local dev with ngrok, this would be like https://abcdef123456.ngrok.io/webhooks/messagebird. Must be HTTPS.
- Events: Select at least message.created and message.updated. You might also want conversation.created, conversation.updated.
- Signing Key: Ensure your generated signing key (from step 1.4) is active.
- Save the webhook.
2. Create Webhooks Module, Controller, and DTO:
nest generate module modules/webhooks
nest generate controller modules/webhooks
mkdir -p src/modules/webhooks/dto
touch src/modules/webhooks/dto/messagebird-webhook.dto.ts
Define Webhook Payload DTO:
Create a DTO to provide basic type safety for the incoming webhook payload.
import { Type } from 'class-transformer';
import { IsString, IsOptional, IsObject, ValidateNested, IsDefined } from 'class-validator';
class MessageContentDto {
@IsOptional() @IsString() text?: string;
@IsOptional() @IsObject() image?: { url: string; caption?: string };
@IsOptional() @IsObject() video?: { url: string; caption?: string };
@IsOptional() @IsObject() audio?: { url: string };
@IsOptional() @IsObject() file?: { url: string; caption?: string };
}
class MessagePayloadDto {
@IsOptional() @IsString() id?: string;
@IsOptional() @IsString() conversationId?: string;
@IsOptional() @IsString() channelId?: string;
@IsOptional() @IsString() from?: string;
@IsOptional() @IsString() to?: string;
@IsOptional() @IsString() direction?: 'incoming' | 'outgoing';
@IsOptional() @IsString() status?: string;
@IsOptional() @IsString() type?: string;
@IsOptional() @ValidateNested() @Type(() => MessageContentDto) content?: MessageContentDto;
@IsOptional() @IsString() createdDatetime?: string;
@IsOptional() @IsString() updatedDatetime?: string;
@IsOptional() @IsObject() error?: { code?: number; description?: string };
}
class ConversationPayloadDto {
@IsOptional() @IsString() id?: string;
@IsOptional() @IsString() contactId?: string;
@IsOptional() @IsString() status?: 'active' | 'archived';
@IsOptional() @IsString() createdDatetime?: string;
@IsOptional() @IsString() updatedDatetime?: string;
}
export class MessageBirdWebhookPayloadDto {
@IsOptional() @ValidateNested() @Type(() => ConversationPayloadDto) conversation?: ConversationPayloadDto;
@IsOptional() @ValidateNested() @Type(() => MessagePayloadDto) message?: MessagePayloadDto;
@IsDefined()
@IsString()
type: 'message.created' | 'message.updated' | 'conversation.created' | 'conversation.updated' | string;
}
3. Implement Webhook Signature Verification (Security):
We need to verify that incoming requests genuinely originate from MessageBird. We'll create a middleware for this.
mkdir -p src/common/middleware
touch src/common/middleware/messagebird-verify.middleware.ts
import { Injectable, NestMiddleware, Logger, ForbiddenException, RawBodyRequest } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
import { ConfigService } from '@nestjs/config';
import * as crypto from 'crypto';
@Injectable()
export class MessageBirdVerifyMiddleware implements NestMiddleware {
private readonly logger = new Logger(MessageBirdVerifyMiddleware.name);
private readonly signingKey: string;
constructor(private configService: ConfigService) {
this.signingKey = this.configService.get<string>('MESSAGEBIRD_WEBHOOK_SIGNING_KEY');
if (!this.signingKey) {
this.logger.error(
'MESSAGEBIRD_WEBHOOK_SIGNING_KEY is not defined. ' +
'Webhook verification will be DISABLED. This is INSECURE for production!'
);
}
}
use(req: RawBodyRequest<Request>, res: Response, next: NextFunction) {
if (!this.signingKey) {
this.logger.warn('CRITICAL: Skipping MessageBird webhook verification as signing key is not configured. THIS IS INSECURE AND MUST NOT HAPPEN IN PRODUCTION.');
return next();
}
const signature = req.headers['messagebird-signature'] as string;
const timestamp = req.headers['messagebird-request-timestamp'] as string;
const requestBody = req.rawBody;
if (!signature || !timestamp || !requestBody) {
this.logger.warn('Missing MessageBird signature headers or body for verification.');
throw new ForbiddenException('MessageBird signature verification failed: Missing headers or body.');
}
try {
const hmac = crypto.createHmac('sha256', this.signingKey);
const signedContent = `${timestamp}.${requestBody.toString('utf8')}`;
const expectedSignature = hmac.update(signedContent).digest('hex');
if (crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expectedSignature))) {
this.logger.log('MessageBird webhook signature verified successfully.');
next();
} else {
this.logger.warn(`Webhook signature mismatch. Expected: ${expectedSignature}, Received: ${signature}`);
throw new ForbiddenException('MessageBird signature verification failed: Invalid signature.');
}
} catch (error) {
this.logger.error('Error during webhook signature verification:', error);
throw new ForbiddenException(`MessageBird signature verification failed: ${error.message}`);
}
}
}
RawBodyRequest: This middleware relies on accessing the raw request body before it's parsed as JSON. We need to enable this in main.ts.
4. Enable Raw Body Parsing:
Modify src/main.ts to enable rawBody.
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ValidationPipe } from '@nestjs/common';
import { NestExpressApplication } from '@nestjs/platform-express';
async function bootstrap() {
const app = await NestFactory.create<NestExpressApplication>(AppModule, {
rawBody: true,
});
app.useGlobalPipes(new ValidationPipe({
whitelist: true,
forbidNonWhitelisted: true,
transform: true,
}));
app.enableCors();
const port = process.env.PORT || 3000;
await app.listen(port);
console.log(`Application is running on: ${await app.getUrl()}`);
}
bootstrap();
5. Implement the Webhooks Controller:
Create an endpoint to receive POST requests from MessageBird. Use the DTO and potentially a validation pipe.
import { Controller, Post, Body, Headers, Logger, HttpCode, HttpStatus, UsePipes, ValidationPipe, Req } from '@nestjs/common';
import { Request } from 'express';
import { MessageBirdWebhookPayloadDto } from './dto/messagebird-webhook.dto';
@Controller('webhooks')
export class WebhooksController {
private readonly logger = new Logger(WebhooksController.name);
constructor(
) {}
@Post('messagebird')
@HttpCode(HttpStatus.OK)
@UsePipes(new ValidationPipe({ skipMissingProperties: true, whitelist: true }))
handleMessageBirdWebhook(
@Body() payload: MessageBirdWebhookPayloadDto,
@Headers('messagebird-signature') signature: string,
@Headers('messagebird-request-timestamp') timestamp: string,
@Req() req: Request
): void {
this.logger.log(`Received MessageBird webhook. Type: ${payload.type}, Signature: ${signature ? 'Present' : 'Missing'}, Timestamp: ${timestamp}`);
this.logger.debug(`Webhook Payload: ${JSON.stringify(payload)}`);
switch (payload.type) {
case 'message.created':
if (payload.message?.direction === 'incoming') {
this.logger.log(`Incoming message received from ${payload.message.from}. Content: ${JSON.stringify(payload.message.content)}`);
} else {
this.logger.log(`Webhook for outgoing message creation (ID: ${payload.message?.id}). Usually handled by message.updated.`);
}
break;
case 'message.updated':
if (payload.message?.direction === 'outgoing') {
this.logger.log(`Status update for outgoing message ${payload.message.id} to ${payload.message.to}: ${payload.message.status}`);
if (payload.message.status === 'failed') {
this.logger.error(`Message ${payload.message.id} failed: ${JSON.stringify(payload.message.error)}`);
}
}
break;
case 'conversation.created':
this.logger.log(`New conversation started: ${payload.conversation?.id}`);
break;
case 'conversation.updated':
this.logger.log(`Conversation ${payload.conversation?.id} updated. Status: ${payload.conversation?.status}`);
break;
default:
this.logger.warn(`Received unhandled webhook event type: ${payload.type}`);
}
}
}
6. Apply Middleware and Register Module:
Apply the MessageBirdVerifyMiddleware specifically to the webhook route in the
WebhooksModule. Then, register WebhooksModule in AppModule.
import { Module, MiddlewareConsumer, NestModule, RequestMethod } from '@nestjs/common';
import { WebhooksController } from './webhooks.controller';
import { MessageBirdVerifyMiddleware } from '../../common/middleware/messagebird-verify.middleware';
@Module({
imports: [
],
controllers: [WebhooksController],
providers: [
],
})
export class WebhooksModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer
.apply(MessageBirdVerifyMiddleware)
.forRoutes({ path: 'webhooks/messagebird', method: RequestMethod.POST });
}
}
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { MessageBirdModule } from './core/messagebird/messagebird.module';
import { WhatsappModule } from './modules/whatsapp/whatsapp.module';
import { WebhooksModule } from './modules/webhooks/webhooks.module';
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
envFilePath: '.env',
}),
MessageBirdModule,
WhatsappModule,
WebhooksModule,
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
7. Testing Webhooks:
- Ensure your NestJS app is running (npm run start:dev).
- Ensure ngrok is running and forwarding to your app's port (ngrok http 3000).
- Ensure the https ngrok URL is configured as the webhook URL in MessageBird for your WhatsApp channel, pointing to /webhooks/messagebird.
- Test Incoming Message: Send a message from your registered Sandbox phone number to the Sandbox WhatsApp number provided by MessageBird. You should see logs in your NestJS console from WebhooksController indicating a message.created event.
- Test Status Update: Send an outgoing message using the /whatsapp/send endpoint (from Step 3). As the message progresses (sent, delivered, read), you should see logs in your NestJS console for message.updated events.
Check the ngrok web interface (http://localhost:4040 by default) to inspect incoming requests
and responses, which is helpful for debugging. Ensure you see 200 OK responses from your webhook
endpoint.
For more WhatsApp Business API integrations and guides, explore these related tutorials:
- Twilio WhatsApp Integration with NestJS - Alternative provider implementation
- Infobip WhatsApp Integration with NestJS - Production-ready integration guide
- Node.js WhatsApp Chatbot Development - Build conversational interfaces
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 β