Tutorials

MessageBird NestJS: Track SMS Delivery Status with Webhooks & Callbacks

Build a production-ready NestJS app to track MessageBird SMS delivery status. Learn webhook implementation, status callbacks, database persistence, and security best practices.

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

Developer Quick-Start: Build a production-ready NestJS app to track MessageBird SMS delivery status. Learn webhook implementation, status callbacks, database persistence, and security best practices. 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.

Sending an SMS successfully is just the first step. To build reliable communication workflows, debug issues, and provide accurate feedback to users or internal systems, you need to know when and if that message reaches the recipient's handset. This MessageBird NestJS guide shows you how to implement SMS delivery tracking with webhooks and callbacks to receive and process real-time status updates.

You'll build a NestJS application that sends SMS messages via MessageBird and includes a dedicated webhook endpoint to receive status updates like sent, delivered, or failed. This guide covers MessageBird webhook configuration, sending messages with callback parameters, handling incoming status callbacks, storing delivery status updates, and production-ready security best practices.

Project Overview and Goals

Goal: Create a NestJS application that sends SMS messages using the MessageBird API and reliably tracks their delivery status through webhooks.

Problem Solved: Gain visibility into SMS delivery beyond the initial API confirmation. Track whether a message was buffered by MessageBird, successfully delivered to the carrier, accepted by the recipient's handset, or failed along the way.

Technologies:

  • NestJS: Progressive Node.js framework for building efficient, reliable, and scalable server-side applications. Provides modular architecture, dependency injection, and strong TypeScript support.
  • MessageBird: Communications platform with APIs for SMS, voice, and more. Offers SMS capabilities and webhook features for status reporting.
  • Node.js: JavaScript runtime environment.
  • TypeScript: Provides type safety and improved developer experience.
  • @nestjs/config: Manages environment variables securely.
  • ngrok (development): Exposes your local server to the internet for webhook testing.
  • (Optional) TypeORM: Persists message details and status updates.

System Architecture:

graph LR
    subgraph Your Application
        Client[Client/Trigger] -- Send Request --> A[NestJS API: /send]
        A -- Save Initial Status (Pending) --> DB[(Database)]
        A -- messagebird.messages.create (with reportUrl & reference) --> MB_API[MessageBird API]
        WB[NestJS API: /status-webhook] -- Update Status --> DB
    end
    subgraph MessageBird Platform
        MB_API -- Sends SMS --> Carrier[Carrier Network] --> UserDevice[User Device]
        MB_API -- Status Update (POST Request) --> WB
    end

    style DB fill:#f9f,stroke:#333,stroke-width:2px

Prerequisites:

  • Node.js (LTS version recommended) and npm or yarn
  • NestJS CLI: npm install -g @nestjs/cli
  • MessageBird account with API credentials (Live Access Key)
  • MessageBird virtual mobile number capable of sending SMS
  • ngrok or similar tunneling service for local development testing
  • Basic understanding of NestJS concepts (modules, controllers, services)
  • (Optional) Docker and Docker Compose for containerized setup

What You'll Build:

A production-ready NestJS application with:

  1. API endpoint to send SMS messages
  2. Webhook endpoint to receive MessageBird delivery status updates
  3. Logic to correlate status updates with original outgoing messages
  4. Secure configuration and comprehensive error handling
  5. (Optional) Database persistence for message status tracking

1. Setting Up the Project

Initialize your NestJS project and install the necessary dependencies.

1. Create NestJS Project:

Open your terminal and run:

nest new messagebird-status-app --strict --package-manager npm
cd messagebird-status-app

This creates a new NestJS project with strict TypeScript configuration and uses npm.

2. Install Dependencies:

npm install messagebird @nestjs/config dotenv

npm install @nestjs/typeorm typeorm pg

npm install uuid
npm install -D @types/uuid

npm install class-validator class-transformer

Package Versions Note: The messagebird package (v4.0.1 as of 2024) is the official Node.js SDK. For TypeORM integration, ensure @nestjs/typeorm version 10.x or later is used with typeorm 0.3.x for compatibility.

3. Environment Variables Setup:

Use environment variables for sensitive information like API keys. Configure @nestjs/config to manage these securely.

  • Create a .env file in the project root:
  #.env

  # MessageBird Configuration
  MESSAGEBIRD_API_KEY=YOUR_LIVE_API_KEY
  # Your purchased MessageBird number (e.g., +12025550135)
  MESSAGEBIRD_ORIGINATOR=YOUR_MESSAGEBIRD_NUMBER

  # Base URL for your webhook endpoint (ngrok URL for development)
  # Example: https://xxxxx.ngrok.io (NO trailing slash)
  CALLBACK_BASE_URL=YOUR_NGROK_OR_PUBLIC_URL

  # (Optional) Database Connection Details (Example for PostgreSQL)
  DB_HOST=localhost
  DB_PORT=5432
  DB_USERNAME=postgres
  DB_PASSWORD=your_db_password
  DB_DATABASE=messagebird_status
  • Important: Replace YOUR_LIVE_API_KEY, YOUR_MESSAGEBIRD_NUMBER, and YOUR_NGROK_OR_PUBLIC_URL with your actual values. Obtain the API key from your MessageBird Dashboard (Developers -> API Access -> Live Key). Purchase a number under the "Numbers" section if you haven't already. The CALLBACK_BASE_URL will be provided by ngrok later.
  • Add .env to your .gitignore file to prevent accidentally committing secrets.

4. Configure ConfigModule and TypeOrmModule (Optional):

Import and configure ConfigModule in your main application module (src/app.module.ts). If using a database, configure TypeOrmModule.

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 { MessagingModule } from './messaging/messaging.module';

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

    *.entity.js').
        autoLoadEntities: true,
        // synchronize: true MUST NOT be used in production.
        // It can lead to data loss. Use migrations instead for schema changes.
        // Recommended ONLY for early development or local testing.
        synchronize: configService.get<string>('NODE_ENV') !== 'production', // Example: Enable only if not in production
      }),
      inject: [ConfigService],
    }),
    */
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

5. Project Structure:

The initial structure created by nest new is suitable. We will add a dedicated messaging module to handle all MessageBird interactions.


2. Implementing Core Functionality (Messaging Module)

We'll create a module responsible for sending messages and handling status callbacks.

1. Generate Module, Service, Controller:

nest g module messaging
nest g service messaging
nest g controller messaging --no-spec

This creates src/messaging/messaging.module.ts, src/messaging/messaging.service.ts, and src/messaging/messaging.controller.ts.

2. Implement MessagingService:

This service will contain the logic for interacting with the MessageBird SDK.

import { Injectable, Logger, InternalServerErrorException, OnModuleInit } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import * as MessageBird from 'messagebird';
import { v4 as uuidv4 } from 'uuid';

@Injectable()
export class MessagingService implements OnModuleInit {
  private readonly logger = new Logger(MessagingService.name);
  private messagebird: MessageBird.MessageBird;
  private originator: string;
  private callbackUrl: string;

  constructor(
      private configService: ConfigService,



    ) {}

  onModuleInit() {
    const apiKey = this.configService.get<string>('MESSAGEBIRD_API_KEY');
    this.originator = this.configService.get<string>('MESSAGEBIRD_ORIGINATOR');
    const baseUrl = this.configService.get<string>('CALLBACK_BASE_URL');

    if (!apiKey || !this.originator || !baseUrl) {
      this.logger.error('MessageBird API Key, Originator, or Callback Base URL not configured.');
      throw new InternalServerErrorException('Messaging service configuration is incomplete.');
    }


    this.messagebird = MessageBird(apiKey);
    this.callbackUrl = `${baseUrl}/messaging/status`;
    this.logger.log('MessageBird SDK initialized.');
    this.logger.log(`Using Originator: ${this.originator}`);
    this.logger.log(`Expecting status callbacks at: ${this.callbackUrl}`);
  }


  async sendMessage(to: string, body: string): Promise<string> {

    const reference = uuidv4();
    this.logger.log(`Attempting to send SMS to ${to} with reference: ${reference}`);












    const params: MessageBird.messages.MessageCreateParameters = {
      originator: this.originator,
      recipients: [to],
      body: body,
      reference: reference,
      reportUrl: this.callbackUrl,
    };

    return new Promise((resolve, reject) => {
      this.messagebird.messages.create(params, async (err, response) => {
        if (err) {
          this.logger.error(`Failed to send SMS via MessageBird: ${err.message}`, err.stack);





          reject(new InternalServerErrorException(`MessageBird API error: ${err.message}`));
        } else {
          const messageBirdId = response?.id;
          if (response?.recipients?.items?.length > 0) {
             this.logger.log(`Message accepted by MessageBird for recipient ${to}. Message ID: ${messageBirdId}, Reference: ${reference}`);






          } else {
             this.logger.warn(`MessageBird response did not contain expected recipient details for ${to}, Reference: ${reference}. Response: ${JSON.stringify(response)}`);

          }
          resolve(reference);
        }
      });
    });
  }


  async processStatusUpdate(statusData: any): Promise<void> {
    const reference = statusData.reference;
    const status = statusData.status;
    const statusDatetime = statusData.statusDatetime;
    let recipient = statusData.recipient;
    const messageId = statusData.id;

    if (!reference) {
      this.logger.warn('Received status update without a reference ID. Cannot correlate.', statusData);
      return;
    }

    this.logger.log(`Received status update for reference ${reference}: Status=${status}, Recipient=${recipient}, Time=${statusDatetime}, MsgID=${messageId}`);













  }
}

Key Points:

  • Initialization (onModuleInit): Initializes the SDK using ConfigService.
  • Unique Reference (uuidv4): Critical for correlating status updates. Generated for each message.
  • reportUrl Parameter: Tells MessageBird where to POST status updates for this specific message.
  • Asynchronous Handling: Uses Promises for cleaner async/await usage.
  • processStatusUpdate: Handles incoming webhook data. Extracts key fields, logs them, and includes placeholder logic for database updates. Normalization of the recipient number is noted as a potential requirement.

3. Implement MessagingController:

Defines API endpoints for sending messages and receiving status updates.

import { Controller, Post, Body, HttpCode, HttpStatus, Logger, ValidationPipe, UsePipes } from '@nestjs/common';
import { MessagingService } from './messaging.service';
import { SendMessageDto } from './dto/send-message.dto';

@Controller('messaging')
export class MessagingController {
  private readonly logger = new Logger(MessagingController.name);

  constructor(private readonly messagingService: MessagingService) {}


  @Post('send')
  @HttpCode(HttpStatus.ACCEPTED)
  @UsePipes(new ValidationPipe({ transform: true, whitelist: true }))
  async sendMessage(@Body() sendMessageDto: SendMessageDto): Promise<{ message: string; reference: string }> {
    this.logger.log(`Received request to send SMS to ${sendMessageDto.to}`);
    const reference = await this.messagingService.sendMessage(
      sendMessageDto.to,
      sendMessageDto.body,
    );
    return {
      message: 'SMS send request accepted by MessageBird.',
      reference: reference,
    };
  }


  @Post('status')
  @HttpCode(HttpStatus.OK)
  async handleStatusWebhook(@Body() statusData: any): Promise<void> {










    await this.messagingService.processStatusUpdate(statusData);








  }
}

Key Points:

  • /send Endpoint: Accepts POST requests, validates input using SendMessageDto, calls the service, returns 202 Accepted with the reference.
  • /status Endpoint: Accepts POST requests from MessageBird. It passes data to the service and must return 200 OK quickly. Slow processing should be handled asynchronously (background job queue recommended).
  • Validation Pipe: Ensures the /send request body adheres to SendMessageDto.

4. Create DTO (Data Transfer Object):

Defines the expected request body for the /send endpoint.

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

export class SendMessageDto {
  @IsNotEmpty()
  @IsPhoneNumber(null)
  @IsString()
  readonly to: string;

  @IsNotEmpty()
  @IsString()
  readonly body: string;
}

3. Building a Complete API Layer

Our core API endpoints (/messaging/send and /messaging/status) are defined. Let's refine them.

Authentication/Authorization:

  • /send Endpoint: This endpoint must be protected (e.g., using API Keys via guards/middleware, or JWT if part of a user session).
  • /status Endpoint: Needs public accessibility but requires security considerations:
  • Obscurity: Use a less guessable path (minor benefit).
  • Shared Secret: Add a secret query parameter to reportUrl and verify it.
  • IP Whitelisting: Allow only MessageBird's webhook IPs (requires infrastructure setup).
  • Signed Webhooks: Verify with current MessageBird documentation if they support cryptographically signed delivery status webhooks. This is the most secure method if available. Check their docs carefully as features evolve.
  • Recommendation: Use HTTPS. Rely on the unique reference for correlation. Rigorously sanitize input. If available and feasible, implement signature verification or IP whitelisting.

Request Validation:

Already implemented for /send using class-validator.

API Documentation:

Consider using @nestjs/swagger to generate OpenAPI documentation for the /send endpoint.

Testing Endpoints:

  • /send Endpoint:
  curl -X POST http://localhost:3000/messaging/send \
       -H 'Content-Type: application/json' \
       -d '{
             "to": "+12025550199",
             "body": "Hello from NestJS and MessageBird!"
           }'
  • /status Endpoint: Test by sending a real message and observing logs/DB, or simulate a callback:
  curl -X POST https://<your-ngrok-url>/messaging/status \
       -H 'Content-Type: application/json' \
       -d '{
             "id": "mb-message-id-123",
             "href": "...",
             "reference": "YOUR_MESSAGE_REFERENCE_ID",
             "status": "delivered",
             "statusDatetime": "2025-04-20T10:30:00Z",
             "recipient": 31612345678,
             "originator": "YourNumber",
             "message": "Hello World"
           }'

4. Integrating with MessageBird

Configuration:

  • API Key: MessageBird Dashboard -> Developers -> API access -> Copy Live Key -> .env (MESSAGEBIRD\_API\_KEY).
  • Virtual Number (Originator): MessageBird Dashboard -> Numbers -> Buy Number -> .env (MESSAGEBIRD\_ORIGINATOR, E.164 format).
  • Webhook URL (reportUrl):
  • Important: MessageBird provides status reports ONLY for SMS messages that have BOTH a reference defined when sending AND a status report URL set via reportUrl (per-message) or configured globally in your account settings.
  • Development: Run ngrok http 3000. Copy HTTPS URL -> .env (CALLBACK\_BASE\_URL). Full URL is ${CALLBACK\_BASE\_URL}/messaging/status.
  • Production: Use your public server URL (e.g., https://api.yourdomain.com) as CALLBACK\_BASE\_URL.
  • Default Status Reports: You can set a global webhook URL in MessageBird settings, but using reportUrl per message (as implemented) offers more control and flexibility.

Environment Variables Summary:

  • MESSAGEBIRD\_API\_KEY: Authenticates API requests.
  • MESSAGEBIRD\_ORIGINATOR: Sender ID for outgoing SMS.
  • CALLBACK\_BASE\_URL: Public base URL for constructing the reportUrl.

Fallback Mechanisms:

  • Implement retries (with backoff) around the sendMessage call in case of transient MessageBird API errors.
  • Log API errors clearly. MessageBird automatically retries webhooks if your /status endpoint fails to return 2xx quickly.

5. Error Handling, Logging, and Retry Mechanisms

Error Handling Strategy:

  • API Sending Errors: Catch errors in sendMessage. Log details. Return appropriate HTTP errors from /send. Optionally update DB status to indicate sending failure.
  • Webhook Processing Errors: Use try...catch in processStatusUpdate. Log internal errors (DB issues, etc.) but always return 200 OK to MessageBird. Handle the failure internally (log, dead-letter queue).
  • Validation Errors: Handled by ValidationPipe for /send (returns 400).

Logging:

  • Use NestJS Logger.
  • Log key events: Init, send attempt (with reference), API success/failure, webhook received (with reference, status), DB updates, errors (with stack traces).
  • Use appropriate levels (log, warn, error).
  • Consider structured logging (JSON) for easier analysis.

Retry Mechanisms:

  • Sending: Implement manual retries with backoff if the initial API call fails due to transient errors.
  • Webhook Receiving: Focus on making /status fast and reliable. MessageBird handles retries if needed. Use a background queue for complex processing.

6. Creating a Database Schema and Data Layer (Optional)

Persistence is needed for tracking. Here's a simplified TypeORM/PostgreSQL example.

Simplified Schema:

For the scope of this guide, a single entity to track the message and its latest status is often sufficient.

erDiagram
    MESSAGE {
        string id PK ""UUID, generated by DB or code""
        string reference UK ""UUID, generated by code, used for correlation""
        string messageBirdId NULL ""MessageBird's internal message ID""
        string recipient ""E.164 phone number""
        string body ""Message content""
        string status ""pending, accepted, sent, delivered, failed, expired, etc.""
        datetime createdAt ""Timestamp when record created""
        datetime statusUpdatedAt NULL ""Timestamp of last status update from MB""
        jsonb lastRawStatus NULL ""Store the last raw JSON payload from webhook""
        datetime updatedAt ""Timestamp record last updated""
    }

2. TypeORM Entity:

import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, UpdateDateColumn, Index } from 'typeorm';

@Entity('messages')
export class Message {
  @PrimaryGeneratedColumn('uuid')
  id: string;


  @Index({ unique: true })
  @Column({ type: 'uuid' })
  reference: string;


  @Index()
  @Column({ nullable: true })
  messageBirdId: string;

  @Column()
  recipient: string;

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


  @Index()
  @Column({ default: 'pending' })
  status: string;

  @CreateDateColumn()
  createdAt: Date;


  @Column({ type: 'timestamptz', nullable: true })
  statusUpdatedAt: Date;


  @Column({ type: 'jsonb', nullable: true })
  lastRawStatus: any;

  @UpdateDateColumn()
  updatedAt: Date;
}

3. Integrate with Service:

Inject the Message repository (@InjectRepository(Message)) into MessagingService constructor. Uncomment and adapt the database interaction logic within sendMessage and processStatusUpdate as shown in the service code comments (Section 2).

4. Migrations:

Strongly recommended for production. Avoid synchronize: true. Use TypeORM migrations.

npm run migration:generate -- InitialMessageSchema

npm run migration:run

(Note: Setting up TypeORM CLI and DataSource is beyond this guide's scope, refer to TypeORM docs)


7. Adding Security Features

  • Input Validation: Done for /send (DTO + ValidationPipe). Sanitize webhook data before use.
  • Authentication: Protect /send (API Key/JWT Guard).
  • Webhook Security:
  • HTTPS Required: Always use HTTPS for webhook endpoints in production.
  • Webhook Signature Verification (Recommended): MessageBird supports HMAC-SHA256 signature verification for webhooks. When configuring your webhook with a signingKey, MessageBird includes MessageBird-Signature and MessageBird-Request-Timestamp headers in webhook requests. Verify these signatures to ensure authenticity:
    import * as crypto from 'crypto';

    function verifyMessageBirdSignature(
      signature: string,
      timestamp: string,
      url: string,
      body: string,
      signingKey: string
    ): boolean {
      const bodyHash = crypto.createHash('sha256').update(body).digest('hex');
      const payload = `${timestamp}\n${url}\n${bodyHash}`;
      const expectedSignature = crypto
        .createHmac('sha256', signingKey)
        .update(payload)
        .digest('hex');
      return signature === expectedSignature;
    }
  • Shared Secret: As an alternative, add a secret query parameter to reportUrl and verify it.
  • IP Whitelisting: Allow only MessageBird's webhook IPs (requires infrastructure setup).
  • Reference Validation: Always verify that incoming webhook reference IDs exist in your system before processing.

8. Handling Special Cases

  • Status Meanings: MessageBird provides three complementary levels of status information that should be analyzed together:
  • Status: High-level message state (e.g., scheduled, sent, buffered, delivered, expired, delivery\_failed)
  • Status Reason: Additional context for the status (reported as statusReason in webhook payload)
  • Error Code: Specific error identifier when applicable (reported as statusErrorCode in webhook payload)

Common status values and their meanings:

  • accepted: Message accepted by MessageBird API
  • sent: Message sent to carrier network
  • buffered: Temporarily held (usually due to carrier issues)
  • delivered: Successfully delivered to recipient's device
  • expired: Message expired before delivery (check validity period)
  • delivery\_failed: Delivery failed (check statusReason and statusErrorCode for details)
  • Time Zones: MessageBird usually provides UTC timestamps. Store in DB using timestamptz (Postgres) or equivalent. Handle time zone conversions carefully.
  • Duplicate Webhooks: Design processStatusUpdate to be idempotent (safe to run multiple times with the same input). Check current status before updating, or use DB constraints.
  • Missing References: Log and monitor webhooks arriving without a reference. This signals an issue.

9. Implementing Performance Optimizations

  • Webhook Response Time: Critical! Ensure /status returns 200 OK quickly. Offload slow tasks (DB writes, external calls) to a background queue (BullMQ, RabbitMQ).
  • Database Indexing: Index reference, status, messageBirdId as shown in the entity.
  • Async Operations: Use async/await correctly, avoid blocking the event loop.
  • Load Testing: Test /send and simulated /status endpoints under load (k6, artillery).
  • Caching: Generally not needed for the webhook itself, but potentially useful elsewhere.

10. Adding Monitoring, Observability, and Analytics

  • Health Checks: Use @nestjs/terminus for a /health endpoint (check DB connection, etc.).
  • Logging: Centralize logs (Datadog, ELK, Loki, CloudWatch). Use structured logging.
  • Metrics: Track rates, latency, error rates (for /send, /status), status distribution, queue lengths (Prometheus, Datadog).
  • Error Tracking: Use Sentry (@sentry/node) or similar for detailed error reporting.
  • Dashboards: Visualize metrics (Grafana, Datadog).
  • Alerting: Set up alerts for critical issues (high errors, failed statuses, latency spikes).

11. Troubleshooting and Caveats

  • Webhook Not Firing: Check ngrok (HTTPS), CALLBACK\_BASE\_URL, reportUrl in API call, app accessibility, firewalls, /status endpoint definition (POST), MessageBird dashboard logs, quick 200 OK response.
  • Cannot Correlate Status: Ensure reference is passed correctly in API call. Check raw webhook payload.
  • Database Issues: Check connection, permissions, logs. Ensure reference exists.
  • Incorrect Status Logic: Verify handling against MessageBird docs.
  • Sender ID Issues: Use purchased numbers for reliability, check country restrictions.
  • Rate Limits: Respect MessageBird API limits; implement backoff/queuing for high volume.
  • Status Delays: Delivery reports can be delayed by carriers; design for asynchronicity.

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