🇺🇸EN
Sign in Get Started
Tutorials

MessageBird SMS Delivery Status Tracking: RedwoodJS Webhook Integration Guide

Complete guide to tracking SMS delivery status with MessageBird webhooks in RedwoodJS. Learn secure webhook verification, real-time status callbacks, and production-ready Node.js implementation.

JH
Jacky Hossein
• Principal Telecommunications Architect • Published Nov 2, 2026 • 17 min read

Developer Quick-Start: Complete guide to tracking SMS delivery status with MessageBird webhooks in RedwoodJS. Learn secure webhook verification, real-time status callbacks, and production-ready Node.js implementation. 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 comprehensive guide shows you how to build a production-ready SMS delivery tracking system using MessageBird webhooks in RedwoodJS. You'll learn how to send SMS messages through the MessageBird API, implement secure webhook signature verification, and track real-time delivery status updates in your Node.js application. We'll cover everything from project setup and database schema design to webhook security, error handling, and GraphQL API integration.

By the end of this MessageBird webhook integration tutorial, you will have a RedwoodJS application capable of:

  • Sending SMS messages using the MessageBird API.
  • Persisting message details and status in a database (PostgreSQL via Prisma).
  • Receiving and securely verifying webhook callbacks from MessageBird to update message delivery status in real-time.
  • Exposing functionality via a GraphQL API.

This solution enables applications to reliably inform users or internal systems about the delivery success or failure of critical SMS communications.

MessageBird SMS Delivery Tracking: Project Overview and Goals

Problem: Many applications send SMS notifications for order confirmations, two-factor authentication (2FA), and alerts, but lack visibility into actual delivery status. Relying on the initial MessageBird API sent confirmation is insufficient—network issues, invalid phone numbers, or carrier blocks can prevent delivery without your knowledge.

Solution: This guide shows you how to implement MessageBird's webhook delivery status callbacks in RedwoodJS. MessageBird sends HTTP POST requests to your webhook endpoint whenever message status changes—from sent to delivered, delivery_failed, or expired. Your application will securely verify webhook signatures using JWT, then update delivery status in real-time in your PostgreSQL database via Prisma ORM.

Technologies Used:

  • RedwoodJS: A full-stack JavaScript/TypeScript framework for the web. It provides structure, conventions, and tools (like Prisma, GraphQL, Jest) out-of-the-box, accelerating development.
  • Node.js: The underlying runtime environment for RedwoodJS.
  • MessageBird: The communications platform as a service (CPaaS) provider used for sending SMS and providing delivery status webhooks.
  • Prisma: The database toolkit used by RedwoodJS for ORM, migrations, and type-safe database access. We'll use it with PostgreSQL.
  • TypeScript: For type safety and improved developer experience.
  • GraphQL: RedwoodJS's default API layer for querying and mutating data.

System Architecture:

+-------------+     +-----------------+     +---------------------+     +---------------+     +-----------------+
| End User/UI | --> | Redwood Web Side| --> | Redwood API (GraphQL)| --> | Message Service | --> | MessageBird API | --> SMS
+-------------+     +-----------------+     +---------------------+     +---------------+     +-----------------+
      ^                                             |                           |                      |
      | (Status Query)                              | (Store Initial Msg        |                      | (Webhook POST)
      |                                             |  & MessageBird ID)        |                      V
      |                                             V                           V                +-----------------+
      +----------------------------------------- (DB Update) <-------------+ Prisma Client <-----+ Webhook Handler | <--+ (Verify Signature)
                                                                          +---------------+     +-----------------+

Prerequisites:

  • Node.js: v18.x or later.
  • Yarn: v1.x (Classic) - RedwoodJS's preferred package manager.
  • RedwoodJS CLI: Install globally: npm install -g redwoodjs
  • PostgreSQL Database: A running instance (local or cloud-based). You'll need the connection string.
  • MessageBird Account: A free or paid account. You'll need:
  • A Live API Key.
  • An SMS-capable Originator (phone number or approved Alphanumeric Sender ID).
  • A Webhook Signing Key.
  • (Optional but Recommended for Local Dev): ngrok or a similar tool to expose your local webhook endpoint to the internet for MessageBird callbacks.

1. Setting up Your RedwoodJS Project for MessageBird Integration

Let's create a new RedwoodJS application and install the MessageBird Node.js SDK for SMS API integration.

  1. Create RedwoodJS App: Open your terminal and run:
   yarn create redwood-app ./messagebird-redwood-status --typescript

This command scaffolds a new RedwoodJS project named messagebird-redwood-status using TypeScript.

  1. Navigate to Project Directory:
   cd messagebird-redwood-status
  1. Install Dependencies: We need the MessageBird Node.js SDK and dotenv for managing environment variables on the API side.
   yarn workspace api add messagebird dotenv
  1. Configure Environment Variables: RedwoodJS uses a .env file at the project root for environment variables. Create this file (touch .env) and add the following, replacing placeholders with your actual credentials:

.env

   # .env

   # --- Database ---
   # Replace with your actual PostgreSQL connection string
   # Format: postgresql://USER:PASSWORD@HOST:PORT/DATABASE
   DATABASE_URL=""postgresql://postgres:password@localhost:5432/messagebird_status""

   # --- MessageBird ---
   # Get from MessageBird Dashboard: Developers -> API access (REST) -> Show key
   MESSAGEBIRD_API_KEY=""YOUR_LIVE_API_KEY""

   # Get from MessageBird Dashboard: Developers -> API access (REST) -> Signing Key
   MESSAGEBIRD_SIGNING_KEY=""YOUR_WEBHOOK_SIGNING_KEY""

   # Your purchased MessageBird number or approved Alphanumeric Sender ID
   # Important: Check country restrictions for Alphanumeric Sender IDs
   MESSAGEBIRD_ORIGINATOR=""YourMessageBirdNumberOrSenderID""

   # The base URL where your Redwood app is deployed (for webhook URL construction)
   # For local dev with ngrok, this would be your ngrok https URL (e.g., https://xxxx.ngrok.io)
   # For production, this is your application's public URL (e.g., https://myapp.com)
   APP_BASE_URL=""http://localhost:8910"" # Default Redwood dev server - CHANGE FOR NGROK/PROD
  • DATABASE_URL: Points to your PostgreSQL instance. Ensure the database exists.
  • Important Security Note: The example DATABASE\_URL uses a weak password (password). Always use strong, unique passwords for your databases, even during development. Consider using a password manager.
  • MESSAGEBIRD_API_KEY: Your live API key from the MessageBird dashboard (Developers -> API access). Treat this like a password.
  • MESSAGEBIRD_SIGNING_KEY: Found below your API keys in the MessageBird dashboard. Used to verify webhook authenticity. Treat this securely.
  • MESSAGEBIRD_ORIGINATOR: The 'From' number or name for outgoing SMS. Must be a number purchased/verified in MessageBird or an approved Alphanumeric Sender ID (check MessageBird documentation for country support).
  • APP_BASE_URL: Crucial for constructing the statusReportUrl sent to MessageBird and the URL you configure in the MessageBird dashboard. Remember to update this when using ngrok or deploying.
  1. Initialize MessageBird Client: Create a reusable MessageBird client instance. Create the file api/src/lib/messagebird.ts:
   import { initClient } from 'messagebird';
   import type { MessageBird } from 'messagebird/types';

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

   const accessKey = process.env.MESSAGEBIRD_API_KEY;

   if (!accessKey) {
     throw new Error(
       'MessageBird API Key not found. Set MESSAGEBIRD_API_KEY in .env'
     );
   }

   const messagebird: MessageBird = initClient(accessKey);

   export default messagebird;
  • This file safely initializes the MessageBird client using the API key from .env.
  • It throws an error during startup if the key is missing, preventing runtime failures later.

2. Implementing SMS Delivery Status Tracking (Database Schema & Services)

To track SMS delivery status, we need a database schema to store message details and real-time status updates from MessageBird webhooks.

  1. Define Database Schema: Open api/db/schema.prisma and define a Message model:

Prisma

   // api/db/schema.prisma

   datasource db {
     provider = ""postgresql""
     url      = env(""DATABASE_URL"")
   }

   generator client {
     provider = ""prisma-client-js""
   }

   model Message {
     id              String    @id @default(cuid()) // Unique DB identifier
     messageBirdId   String?   @unique // MessageBird's unique ID for the message
     recipient       String    // E.164 format phone number
     body            String    // Message content
     status          String    @default(""pending"") // e.g., pending, sent, delivered, failed, expired
     statusDetails   String?   // Optional extra details from webhook
     statusUpdatedAt DateTime? // Timestamp of the last status update from webhook
     createdAt       DateTime  @default(now())
     updatedAt       DateTime  @updatedAt

     // Optional: Link to another record in your application
     // relatedRecordId String?
     // relatedRecord   RelatedModel? @relation(fields: [relatedRecordId], references: [id])

     @@index([status]) // Add index for faster status queries
   }

   // Example of relating to another model (uncomment and define RelatedModel if needed)
   // model RelatedModel {
   //   id       String @id @default(cuid())
   //   messages Message[]
   // }
  • id: Standard CUID primary key.
  • messageBirdId: Stores the ID returned by MessageBird when a message is created. This is crucial for correlating webhook updates. It's nullable initially and marked unique.
  • recipient, body: Basic message details.
  • status: Tracks the delivery status. Defaults to pending.
  • Note on status Type: Using String provides flexibility if MessageBird introduces new status values not defined in your code. However, using a Prisma enum (e.g., enum MessageStatus { PENDING, QUEUED, SENT, DELIVERED, FAILED, EXPIRED }) offers better type safety and clearly defines allowed states within your application code. Choose based on whether you prioritize flexibility or strict type checking.
  • statusDetails: Can store additional error information from failed delivery webhooks.
  • statusUpdatedAt: Timestamp from the webhook event.
  • createdAt, updatedAt: Standard Prisma timestamps.
  • (Optional) relatedRecordId/relatedRecord: Shows how you might link this message back to another entity in your app (like an Order or User).
  • @@index([status]): Added an index to the status field for potentially faster queries filtering by status.
  1. Apply Database Migrations: Create and apply the migration to your database:
   yarn rw prisma migrate dev --name add_message_model

Follow the prompts. This creates the Message table in your PostgreSQL database and applies the index.

  1. Generate GraphQL SDL and Services: Use Redwood's generators to create the boilerplate for GraphQL types, queries, mutations, and the service file for the Message model:
   yarn rw g sdl Message --crud

This command creates:

  • api/src/graphql/messages.sdl.ts: Defines GraphQL types (Message), queries (messages, message), and mutations (createMessage, updateMessage, deleteMessage).
  • api/src/services/messages/messages.ts: Contains Prisma logic for the generated queries/mutations.
  • api/src/services/messages/messages.scenarios.ts: For defining seed data for tests.
  • api/src/services/messages/messages.test.ts: Basic test structure.
  1. Implement Message Sending Service: Modify the generated api/src/services/messages/messages.ts to handle sending SMS via MessageBird and integrate the webhook logic. We'll replace the default createMessage with a custom sendMessage mutation and add a function to handle webhook updates.
   import type { QueryResolvers, MutationResolvers, MessageRelationResolvers } from 'types/graphql';
   import { Prisma } from '@prisma/client';

   import { db } from 'src/lib/db';
   import messagebird from 'src/lib/messagebird';
   import { logger } from 'src/lib/logger';

   export interface MessageBirdWebhookPayload {
     id: string;
     status: string;
     statusDatetime: string;
     statusReason?: string;

   }

   export const sendMessage: MutationResolvers['sendMessage'] = async ({ input }) => {
     const { recipient, body } = input;


     if (!recipient || !body) {
       throw new Error('Recipient and body are required.');
     }



     const appBaseUrl = process.env.APP_BASE_URL;
     if (!appBaseUrl) {
       logger.error('APP_BASE_URL environment variable is not set.');
       throw new Error('Application base URL is not configured.');
     }


     const statusReportUrl = `${appBaseUrl}/.redwood/functions/messagebirdWebhook`;


     let dbMessage;
     try {
       dbMessage = await db.message.create({
         data: {
           recipient,
           body,
           status: 'queued',
         },
       });
       logger.info({ messageId: dbMessage.id }, 'Created initial message record.');
     } catch (error) {
       logger.error({ error }, 'Failed to create initial message record in DB.');

       throw new Error('Database error while preparing message.');
     }


     const originator = process.env.MESSAGEBIRD_ORIGINATOR;
     if (!originator) {
       logger.error('MESSAGEBIRD_ORIGINATOR environment variable is not set.');

       await db.message.update({ where: { id: dbMessage.id }, data: { status: 'config_error', statusDetails: 'Originator not set' } });
       throw new Error('MessageBird Originator is not configured.');
     }

     try {
       logger.info({ recipient, originator, statusReportUrl }, 'Attempting to send SMS via MessageBird');

       const params = {
         originator: originator,
         recipients: [recipient],
         body: body,
         statusReportUrl: statusReportUrl,

       };


       const response = await new Promise<any>((resolve, reject) => {
          messagebird.messages.create(params, (err, resp) => {
           if (err) {

              logger.error({ err, dbMessageId: dbMessage.id }, 'MessageBird API error during send.');
              return reject(err);
            }
            logger.info({ response, dbMessageId: dbMessage.id }, 'MessageBird API send successful.');
            resolve(resp);
          });
        });


       if (response?.id) {
         const updatedMessage = await db.message.update({
           where: { id: dbMessage.id },
           data: {
             messageBirdId: response.id,
             status: 'sent',
           },
         });
         logger.info({ messageBirdId: response.id, dbMessageId: dbMessage.id }, 'Updated DB record with MessageBird ID.');
         return updatedMessage;
       } else {

         logger.warn({ response, dbMessageId: dbMessage.id }, 'MessageBird API response missing expected ID.');

          await db.message.update({ where: { id: dbMessage.id }, data: { status: 'send_issue', statusDetails: 'API response missing ID' } });
          throw new Error('Message submission issue: No MessageBird ID received.');
       }

     } catch (error) {
       logger.error({ error, dbMessageId: dbMessage.id }, 'Failed to send message via MessageBird API.');


       const errorMessage = error.message || (error.errors ? JSON.stringify(error.errors) : 'Unknown API error');
       await db.message.update({
         where: { id: dbMessage.id },
         data: { status: 'failed_to_send', statusDetails: errorMessage },
       });

       throw new Error(`Failed to send message: ${errorMessage}`);
     }
   };

   export const updateMessageStatusFromWebhook = async (payload: MessageBirdWebhookPayload): Promise<boolean> => {
     logger.info({ payload }, 'Received request to update message status from webhook');

     const { id: messageBirdId, status, statusDatetime, statusReason } = payload;

     if (!messageBirdId) {
       logger.warn({ payload }, 'Webhook payload missing messageBirdId. Cannot process.');

       return false;
     }

     try {

       const updatedMessage = await db.message.update({
         where: { messageBirdId: messageBirdId },
         data: {
           status: status,
           statusDetails: statusReason,
           statusUpdatedAt: new Date(statusDatetime),
         },
       });
       logger.info(
         { messageBirdId, newStatus: status, dbMessageId: updatedMessage.id },
         'Successfully updated message status from webhook.'
       );
       return true;

     } catch (error) {

       if (error instanceof Prisma.PrismaClientKnownRequestError && error.code === 'P2025') {




          logger.warn({ messageBirdId }, 'MessageBird ID from webhook not found in database (Prisma code P2025). Update skipped.');



          return true;
        } else {

          logger.error({ error, messageBirdId }, 'Database error updating message status from webhook.');
          return false;
        }
     }
   };

   export const messages: QueryResolvers['messages'] = () => {

     return db.message.findMany();
   };

   export const message: QueryResolvers['message'] = ({ id }) => {

     return db.message.findUnique({
       where: { id },
     });
   };

   export const updateMessage: MutationResolvers['updateMessage'] = ({ id, input }) => {


     logger.warn({ id, input }, 'Direct message update via GraphQL called.');
     return db.message.update({
       data: input,
       where: { id },
     });
   };

   export const deleteMessage: MutationResolvers['deleteMessage'] = ({ id }) => {


     logger.warn({ id }, 'Direct message delete via GraphQL called.');
     return db.message.delete({
       where: { id },
     });
   };

   export const Message: MessageRelationResolvers = {




   };
  • sendMessage:
  • Takes recipient and body as input.
  • Constructs the statusReportUrl using APP\_BASE\_URL and the exact path to the Redwood function we'll create (/.redwood/functions/messagebirdWebhook).
  • Creates a Message record in the DB with status queued.
  • Calls messagebird.messages.create, passing the statusReportUrl.
  • Uses a Promise wrapper around the callback-based SDK method for better async/await flow.
  • If successful, updates the DB record with the messageBirdId from the response and sets status to sent.
  • Includes enhanced error handling and logging for DB and API call failures, updating the DB status accordingly (e.g., config\_error, failed\_to\_send, send\_issue).
  • updateMessageStatusFromWebhook:
  • Takes the verified webhook payload, strongly typed with MessageBirdWebhookPayload (which is now exported).
  • Finds the corresponding Message record using the unique messageBirdId.
  • Updates the status, statusDetails, and statusUpdatedAt fields.
  • Logs success or failure, specifically handling the P2025 (Record Not Found) Prisma error as a non-critical warning. Returns a boolean indicating success/failure.
  • Standard CRUD: The original createMessage is removed/commented out with warnings. updateMessage and deleteMessage are kept but include warnings and TODOs for adding authorization, as direct manipulation might bypass business logic or security checks.

3. Building the GraphQL API for SMS Operations

RedwoodJS generates GraphQL schema boilerplate. We'll customize it to expose a sendMessage mutation for sending SMS with delivery tracking enabled.

  1. Update GraphQL Schema Definition: Modify api/src/graphql/messages.sdl.ts:
   export const schema = gql`
     scalar DateTime

     type Message {
       id: String!
       messageBirdId: String
       recipient: String!
       body: String!
       status: String!
       statusDetails: String
       statusUpdatedAt: DateTime
       createdAt: DateTime!
       updatedAt: DateTime!

     }

     type Query {
       messages: [Message!]! @requireAuth
       message(id: String!): Message @requireAuth
     }


     input CreateMessageInput {
       messageBirdId: String
       recipient: String!
       body: String!
       status: String
       statusDetails: String
       statusUpdatedAt: DateTime

     }


     input UpdateMessageInput {
       messageBirdId: String
       recipient: String
       body: String
       status: String
       statusDetails: String
       statusUpdatedAt: DateTime

     }


     input SendMessageInput {
       recipient: String!
       body: String!


     }

     type Mutation {

       sendMessage(input: SendMessageInput!): Message! @requireAuth



       updateMessage(id: String!, input: UpdateMessageInput!): Message! @requireAuth
       deleteMessage(id: String!): Message! @requireAuth
     }
   `;
  • Added the SendMessageInput type for our custom mutation.
  • Replaced the default createMessage mutation with sendMessage(input: SendMessageInput!): Message!.
  • Kept the standard Message type, queries (messages, message), and other mutations (updateMessage, deleteMessage).
  • Added comments reminding to implement proper authorization (@requireAuth is a basic check, might need role-based access) if the standard update/delete mutations are exposed.
  • Ensured the scalar DateTime definition is present (often included by default).
  1. Testing the Mutation (Conceptual): You can use the Redwood GraphQL Playground (usually available at http://localhost:8911/graphql when running yarn rw dev) to test the sendMessage mutation.

Example GraphQL Mutation:

   mutation SendTestMessage {
     sendMessage(input: {
       recipient: ""+1xxxxxxxxxx""
       body: ""Hello from RedwoodJS + MessageBird! Testing status updates.""
     }) {
       id
       messageBirdId
       recipient
       status
       createdAt
     }
   }
  • Executing this should trigger the sendMessage service function, create a DB record, call the MessageBird API, update the record with the messageBirdId and sent status, and return the result.

4. Implementing MessageBird Webhook Handler for Delivery Status Callbacks

The webhook handler is essential for receiving real-time SMS delivery status updates from MessageBird. We'll create a dedicated RedwoodJS serverless function to handle incoming POST requests, verify webhook signatures, and update message status in the database.

  1. Create Redwood Function: Use the Redwood generator:
   yarn rw g function messagebirdWebhook --typescript

This creates api/src/functions/messagebirdWebhook.ts.

  1. Implement Webhook Handler and Signature Verification: Edit api/src/functions/messagebirdWebhook.ts to verify the signature and process the payload:
   import type { APIGatewayEvent, Context, APIGatewayProxyResult } from 'aws-lambda';
   import { WebhookSignatureJwt } from 'messagebird/lib/webhook-signature-jwt';
   import { logger } from 'src/lib/logger';

   import { updateMessageStatusFromWebhook, MessageBirdWebhookPayload } from 'src/services/messages/messages';

   const signingKey = process.env.MESSAGEBIRD_SIGNING_KEY;

   if (!signingKey) {
     logger.fatal('MESSAGEBIRD_SIGNING_KEY is not set. Cannot verify webhooks.');


   }

   const verifier = signingKey ? new WebhookSignatureJwt(signingKey) : null;

   export const config = {
     api: {
       bodyParser: false,
     },
   };

   export const handler = async (event: APIGatewayEvent, _context: Context): Promise<APIGatewayProxyResult> => {
     logger.info('Received request on messagebirdWebhook function.');

     if (!verifier) {
       logger.error('Webhook signature verifier not initialized (missing signing key). Denying request.');
       return { statusCode: 500, body: 'Internal Server Error: Webhook verification not configured.' };
     }

     if (event.httpMethod !== 'POST') {
       logger.warn(`Received non-POST request: ${event.httpMethod}. Method Not Allowed.`);
       return { statusCode: 405, body: 'Method Not Allowed' };
     }


     const signatureHeader = event.headers['messagebird-signature-jwt'];
     const queryParams = event.queryStringParameters || {};
     const rawBody = event.body;

     if (!signatureHeader) {
       logger.warn('Missing MessageBird-Signature-JWT header. Denying request.');
       return { statusCode: 401, body: 'Unauthorized: Missing signature.' };
     }

     if (!rawBody) {
       logger.warn('Request body is empty. Cannot verify signature or process payload.');

       return { statusCode: 400, body: 'Bad Request: Empty body.' };
     }






     const appBaseUrl = process.env.APP_BASE_URL;
     if (!appBaseUrl) {
       logger.error('APP_BASE_URL is not set. Cannot reliably reconstruct request URL for verification.');
       return { statusCode: 500, body: 'Internal Server Error: Application URL not configured.' };
     }
     const path = event.path;
     const requestUrl = `${appBaseUrl}${path}`;

     try {

       verifier.verify(signatureHeader, requestUrl, queryParams, rawBody);
       logger.info('MessageBird webhook signature verified successfully.');

     } catch (error) {
       logger.error({ error }, 'Invalid MessageBird webhook signature. Denying request.');
       return { statusCode: 401, body: 'Unauthorized: Invalid signature.' };
     }


     let payload: MessageBirdWebhookPayload;
     try {

       payload = JSON.parse(rawBody);
       logger.info({ messageBirdId: payload.id, status: payload.status }, 'Parsed webhook payload.');


       if (!payload.id || !payload.status || !payload.statusDatetime) {
         logger.warn({ payload }, 'Webhook payload missing required fields (id, status, statusDatetime).');

         return { statusCode: 400, body: 'Bad Request: Invalid payload structure.' };
       }

     } catch (error) {
       logger.error({ error, rawBody }, 'Failed to parse webhook JSON payload.');

       return { statusCode: 400, body: 'Bad Request: Invalid JSON payload.' };
     }


     try {
       const updateSuccessful = await updateMessageStatusFromWebhook(payload);

       if (updateSuccessful) {
         logger.info({ messageBirdId: payload.id }, 'Webhook processed and database updated successfully.');

         return { statusCode: 200, body: 'Webhook processed successfully.' };
       } else {

         logger.error({ messageBirdId: payload.id }, 'Failed to update database from webhook (service function returned false).');


         return { statusCode: 500, body: 'Internal Server Error: Failed to update message status.' };
       }
     } catch (error) {

       logger.error({ error, messageBirdId: payload.id }, 'Unexpected error calling updateMessageStatusFromWebhook.');
       return { statusCode: 500, body: 'Internal Server Error: Unexpected error processing webhook.' };
     }
   };
  • Signature Verification:
  • Imports WebhookSignatureJwt from the MessageBird SDK.
  • Loads the MESSAGEBIRD\_SIGNING\_KEY from .env.
  • Crucially, includes export const config = { api: { bodyParser: false } }; to ensure event.body contains the raw request string needed for verification.
  • Instantiates the verifier outside the handler.
  • Checks for POST method and the presence of the MessageBird-Signature-JWT header.
  • Reconstructs the requestUrl using APP_BASE_URL and event.path. This is a critical step and needs careful testing in deployment.
  • Calls verifier.verify with the signature, reconstructed URL, query parameters (event.queryStringParameters), and the raw body (event.body).
  • Returns 401 Unauthorized if verification fails.
  • Payload Processing:
  • Parses the rawBody into a JSON object only after successful signature verification.
  • Performs basic validation on the parsed payload to ensure required fields exist.
  • Returns 400 Bad Request if parsing or validation fails.
  • Database Update:
  • Calls the updateMessageStatusFromWebhook service function with the validated payload.
  • Returns 200 OK if the service function indicates success (returns true).
  • Returns 500 Internal Server Error if the service function indicates failure (returns false) or if an unexpected error occurs, potentially prompting MessageBird to retry.

Looking to expand your MessageBird SMS integration? Check out these related guides:

  • Sending SMS with MessageBird in RedwoodJS - Learn the basics of MessageBird SMS API integration
  • MessageBird MMS Integration with RedwoodJS - Add multimedia messaging capabilities
  • Two-Way SMS Messaging with MessageBird - Handle incoming SMS replies

MessageBird Webhook Integration FAQ

How do I verify MessageBird webhook signatures in RedwoodJS?

Use the WebhookSignatureJwt class from the MessageBird SDK. Import it with import { WebhookSignatureJwt } from 'messagebird/lib/webhook-signature-jwt', then instantiate it with your signing key and call verifier.verify() with the signature header, request URL, query parameters, and raw body. You must disable RedwoodJS's automatic body parser by exporting config = { api: { bodyParser: false } } in your function file to access the raw request body required for verification.

What is the correct way to initialize the MessageBird SDK in Node.js?

Use initClient() from the MessageBird SDK: import { initClient } from 'messagebird'; const messagebird = initClient('YOUR_API_KEY');. The SDK uses a callback-based API, so wrap methods in Promises for async/await support: await new Promise((resolve, reject) => { messagebird.messages.create(params, (err, resp) => err ? reject(err) : resolve(resp)); }).

How does MessageBird's statusReportUrl parameter work?

The statusReportUrl parameter tells MessageBird where to send HTTP POST requests when your message's delivery status changes. Include it when creating a message: messagebird.messages.create({ originator, recipients, body, statusReportUrl }). MessageBird will send webhooks to this URL with status updates like delivered, delivery_failed, or expired.

Why do I need to set bodyParser: false in RedwoodJS functions?

MessageBird's JWT signature verification requires the raw, unparsed request body to validate the signature. RedwoodJS normally parses JSON bodies automatically, which modifies the body string and breaks signature verification. Setting export const config = { api: { bodyParser: false } } in your function file prevents automatic parsing, letting you access event.body as the original raw string needed for verification.

What MessageBird message statuses should I handle in my webhook?

Handle these key statuses: sent (message left MessageBird's platform), buffered (queued for delivery), delivered (successfully received by handset), delivery_failed (permanent failure), and expired (validity period exceeded). The webhook payload includes status, statusReason, and optionally statusErrorCode for detailed failure information.

How do I test MessageBird webhooks locally with RedwoodJS?

Use RedwoodJS's mockSignedWebhook testing utility to simulate webhooks without external tools: const event = mockSignedWebhook({ payload, signatureType: 'sha256Verifier', signatureHeader: 'MessageBird-Signature-JWT', secret: 'YOUR_SIGNING_KEY' }). This creates a properly signed test event you can pass to your handler in unit tests. For live testing, use ngrok to expose your local server and configure the ngrok URL in MessageBird's dashboard.

What happens if MessageBird sends duplicate webhook deliveries?

MessageBird may retry webhooks up to 10 times if it doesn't receive a 200 OK response. Implement idempotency by using MessageBird's unique message ID (messageBirdId) as your database lookup key. Prisma's update with a where clause on the unique messageBirdId field ensures duplicate webhooks safely update the same record without creating duplicates.

How do I configure the webhook URL in MessageBird's dashboard?

MessageBird doesn't provide a programmatic API for webhook URL configuration. You must configure it manually through the Flow Builder dashboard. For status reports, pass the statusReportUrl parameter when creating each message. For inbound messages, configure the webhook URL in Flow Builder using the "Forward to URL" step.

What security measures should I implement for MessageBird webhooks?

Always verify the MessageBird-Signature-JWT header using your signing key before processing payloads. Return 401 Unauthorized for invalid signatures. Validate the webhook payload structure before database operations. Consider implementing rate limiting to prevent abuse. Store your signing key securely in environment variables, never in code. Use HTTPS in production to prevent man-in-the-middle attacks.

How do I handle webhook failures and retries in RedwoodJS?

Return appropriate HTTP status codes: 200 OK when successfully processed (stops retries), 401 Unauthorized for signature failures (stops retries), and 500 Internal Server Error for temporary issues (triggers MessageBird retries). Log all webhook attempts with logger.info() for debugging. MessageBird will retry failed webhooks up to 10 times with exponential backoff, so design your handler to be idempotent.

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 →