Frequently Asked Questions
Use the MessageBird Node.js SDK and Express.js to create a POST route that handles sending SMS messages. This route should extract recipient and message details from the request body, construct the necessary parameters for the MessageBird API, and use the SDK's messages.create()
method to send the SMS. Remember to store the returned message ID for tracking delivery status.
A webhook is a mechanism for receiving real-time updates from MessageBird about the status of your sent messages (like 'delivered', 'sent', or 'failed'). MessageBird sends an HTTP POST request to a URL you specify, containing the status details. In your application, create an Express route to handle these incoming requests.
Dotenv loads environment variables from a .env
file. This is essential for securely storing sensitive information, like your MessageBird API key, and preventing it from being exposed in your source code or version control systems like Git. Add your API key to the .env
file with MESSAGEBIRD_API_KEY=YOUR_API_KEY
.
ngrok is useful during development to expose your local server to the internet, allowing you to receive MessageBird webhooks. Since webhooks require a publicly accessible URL, ngrok creates a secure tunnel. It's a development tool; in production, you would use your deployed server's public URL.
Yes, the MessageBird API supports sending SMS messages to multiple recipients. In the recipients
parameter of your messagebird.messages.create
request, provide an array of phone numbers in E.164 format. Ensure you handle responses and status updates for each recipient individually if needed.
Implement a webhook handler in your Express app as a POST route (e.g., /messagebird-status
). This route will receive status updates from MessageBird. Extract the message ID from the request body to correlate it with the original message you sent. Store status updates in a database for persistent tracking.
The message ID is a unique identifier assigned by MessageBird to each SMS message you send. It's crucial for correlating delivery status updates received via webhooks with the original message. You'll use this ID to look up and update the message status in your database.
Acknowledge the webhook by responding with a 2xx HTTP status (e.g., 200 OK) even if errors occur in your processing logic. This prevents MessageBird from retrying the webhook unnecessarily. Log internal errors thoroughly for investigation and implement retry mechanisms or queueing where applicable.
You should use a persistent database for production applications. The tutorial demonstrates setting up MongoDB (install mongodb
driver, connect, insert, update). Other suitable databases include PostgreSQL, MySQL, or cloud-based solutions like MongoDB Atlas or Google Cloud Firestore.
In the MessageBird dashboard, go to Developers > API access or Flow Builder, then configure the URL for your webhook handler. This URL should be publicly accessible, so you may use ngrok for local development. In production, use your server's domain/IP + route path. The webhook receives POST requests from MessageBird.
E.164 is an international standard phone number format (+[country code][number]). It's essential for ensuring compatibility and proper delivery of SMS messages globally. Always format numbers in E.164 before sending them to the MessageBird API.
Use a test API key during development to integrate with MessageBird's platform without incurring real SMS costs. Test keys help verify that API requests are structured correctly and that webhook setups are working as expected. Switch to your live API key once you're ready to send actual messages.
Use npm or yarn to install the required packages. The article outlines these: npm install express messagebird dotenv
for the main dependencies and npm install --save-dev nodemon
for development tools (nodemon auto-restarts your server during coding).
Nodemon automatically restarts your Node.js server whenever you make changes to your code. It's a development convenience tool that saves you from manually restarting the server every time you edit a file, speeding up development considerably. Install with npm as dev dependency.
MessageBird SMS Delivery Status & Webhooks: Complete Node.js Express Guide
Build a production-ready webhook system to track SMS delivery status in real time using MessageBird's REST API. This comprehensive tutorial shows you how to send SMS messages and receive instant delivery updates through MessageBird webhooks using Node.js and Express. You'll implement HMAC-SHA256 signature verification, status code handling, retry logic, and production security with complete working code examples.
What You'll Build
Create an SMS tracking system with:
Why Use Webhooks for SMS Delivery Tracking?
Webhook vs. polling performance comparison:
Webhooks deliver immediate notification when message status changes, eliminating polling. MessageBird sends instant updates when messages are sent, delivered, failed, or expired.
Benefits of webhook-based delivery tracking:
How to Set Up Your MessageBird Node.js Project
System requirements:
According to MessageBird's official Node.js documentation, the MessageBird Node.js SDK requires Node.js 0.10 at minimum. For production deployments in 2025, use Node.js 18.18 LTS or later for security updates and performance improvements.
Initialize your Node.js project and install dependencies:
Package overview:
Where to Obtain MessageBird API Keys
To get your MessageBird Access Key:
live_
for production ortest_
for testing)To get your MessageBird Signing Key:
sk_
)Official MessageBird API documentation provides detailed information on API key management and security best practices.
Create your
.env
file with MessageBird credentials:Security note: Never commit your
.env
file to version control. Add it to.gitignore
immediately.How to Send SMS Messages with MessageBird
Create a function to send SMS using the MessageBird SDK. Before receiving webhook delivery updates, send SMS messages:
Key parameters explained:
+14155552671
)Test the SMS function:
When the message sends successfully, MessageBird returns a message ID. This ID appears in webhook payloads for delivery status tracking. According to MessageBird's SMS tutorial, you can track message delivery through webhooks or by polling the Messages API. For more information on phone number formatting, see the E.164 phone number format guide.
How to Verify Webhook Signatures with HMAC-SHA256
MessageBird signs all webhook requests with HMAC-SHA256 cryptographic signatures to prevent unauthorized access and replay attacks. Always verify webhook signatures before processing the payload to ensure security.
Understanding Webhook Signature Verification
Webhook signature verification ensures incoming requests originate from MessageBird and haven't been tampered with. MessageBird generates a cryptographic signature using your signing key and includes it in the
MessageBird-Signature-JWT
header.Why signature verification matters:
How to Implement Signature Verification
Create a middleware file to verify all incoming webhooks:
Important security considerations:
url_hash
,payload_hash
,jti
,nbf
,exp
exp
(expiration) claim to prevent processing stale requestsSet
works for single-server deployments but doesn't persist across restarts. For production clusters with multiple servers, store JTIs in Redis with 1-hour TTL. Memory usage: ~50 bytes per JTI; 1 million webhooks ≈ 50 MB memory.Where to Find Your MessageBird Signing Key
sk_
).env
file asMESSAGEBIRD_SIGNING_KEY
Security warning: Never expose your signing key in client-side code or public repositories.
Understanding SMS Delivery Status Codes
MessageBird provides three levels of status information to track every stage of SMS delivery:
Primary Status Codes
sent
buffered
delivered
delivery_failed
statusReason
andstatusErrorCode
for root causeexpired
Status transition timing expectations:
delivered
status within 2–10 secondsbuffered
status)expired
statusErrorCode: 6
) may resolve within minutes to hoursSecondary Status Reasons
The
statusReason
field provides additional context about delivery failures:Tertiary Error Codes
The
statusErrorCode
field provides carrier-specific error details:Example webhook payload with all status levels:
How to Handle SMS Delivery Status Codes
Implement appropriate actions based on status with exponential backoff retry logic:
How to Build a Webhook Endpoint in Express
Create your Express server with webhook handling and SMS sending integration:
Key implementation details:
findOneAndUpdate
withupsert
prevents duplicate processingmessageId
field is unique and indexed for fast lookups/api/send-sms
endpoint sends messages and stores initial records; webhook updates delivery statusHow to Test Webhooks Locally with Ngrok
Ngrok creates a secure HTTPS tunnel to your local development server, enabling MessageBird to deliver webhook callbacks during testing. Learn more about webhook testing best practices in MessageBird's developer documentation.
Understanding Ngrok for Local Webhook Testing
Ngrok exposes your localhost server to the internet with a public URL. MessageBird requires HTTPS webhooks, which ngrok provides automatically with valid SSL certificates.
Install and start ngrok:
Ngrok output:
Copy the HTTPS forwarding URL (e.g.,
https://abc123.ngrok.io
).Configuring Webhooks in MessageBird Dashboard
https://abc123.ngrok.io/webhooks/delivery-status
Testing tips:
http://localhost:4040
to debug webhook payloadsCommon ngrok troubleshooting:
npm update -g ngrok
Production Security Best Practices for Webhooks
Implement these security measures before deploying to production:
1. HTTPS Enforcement
Force HTTPS for all webhook endpoints:
2. Rate Limiting
Install the rate limiting package:
Prevent abuse with rate limiting:
3. Timestamp Validation
Integrate timestamp validation into webhook handler to reject stale requests:
4. IP Allowlisting
Important note: According to MessageBird's official documentation, MessageBird's REST API uses dynamic IP addresses from globally distributed infrastructure, making IP allowlisting impractical. MessageBird recommends using signature verification (covered above) instead of IP filtering.
Alternative: Signature verification is mandatory
MessageBird explicitly states: "It will not be possible to whitelist the IP range for our REST API since our IP addresses are dynamic." Instead, always implement webhook signature verification using the signing key method described in this guide. This provides stronger security than IP allowlisting while accommodating MessageBird's distributed architecture.
If your organization requires network-level security, implement these alternatives:
5. JTI Persistence with Redis
For production deployments with multiple servers, store JWT IDs in Redis:
Implement distributed JTI tracking:
Monitoring and Debugging Webhook Deliveries
Viewing Webhook Delivery Logs in Dashboard
MessageBird Dashboard provides comprehensive webhook activity logs:
Common debugging scenarios:
Testing Webhook Endpoints Locally
Important note: Testing webhooks with curl requires generating valid JWT signatures. The MessageBird SDK handles signature generation automatically for real webhooks. For local testing, use these approaches:
Option 1: Bypass signature verification for testing (NOT for production):
Test with curl:
Option 2: Send real SMS and monitor webhooks (recommended):
/api/send-sms
endpointTesting checklist:
sent
,delivered
,delivery_failed
,expired
Frequently Asked Questions
How do I verify webhook signatures?
MessageBird signs webhooks with HMAC-SHA256 and sends the signature in the
MessageBird-Signature-JWT
header. Use the official MessageBird SDK'swebhook-signature-jwt
module to verify signatures automatically. The SDK validates the JWT structure, expiration, and payload hash. Implement JTI (JWT ID) verification to prevent replay attacks by tracking processed JWT IDs in memory or Redis.What are MessageBird's webhook retry policies?
MessageBird retries failed webhook deliveries using exponential backoff. If your endpoint returns a non-2xx status code or times out, MessageBird retries up to 10 times over 24 hours. The retry schedule: immediate, 1 minute, 5 minutes, 30 minutes, 1 hour, 3 hours, 6 hours, 12 hours, and 24 hours. Return HTTP 200 OK for successful processing, even if business logic fails internally.
What SMS delivery status codes does MessageBird provide?
MessageBird provides three status levels:
status
(primary),statusReason
(secondary), andstatusErrorCode
(tertiary). Primary statuses:sent
,buffered
,delivered
,delivery_failed
, andexpired
. Status reasons:absent_subscriber
,invalid_destination
,unknown_subscriber
,rejected_by_carrier
, andblacklisted
. Error codes: 0 (no error), 5 (permanent failure), 6 (temporary failure), 9 (unknown error).How do I handle duplicate webhooks?
Implement idempotent webhook processing using the message ID as a unique identifier. Use database operations like
findOneAndUpdate
withupsert
to handle duplicates safely. Track JWT IDs (jti claim) in memory or Redis to detect and reject duplicate deliveries. MessageBird may send the same webhook multiple times during network issues or retries.Why is my webhook endpoint timing out?
MessageBird requires webhook endpoints to respond within 5 seconds. Return HTTP 200 OK immediately after receiving the webhook, then process heavy operations asynchronously. Use job queues like Bull or BullMQ for background processing:
Optimize database queries with proper indexing. Avoid synchronous external API calls in webhook handlers. Monitor endpoint response times with APM tools.
What security measures should I implement for webhooks?
Implement these security measures: (1) Always verify webhook signatures using the signing key, (2) Enforce HTTPS in production, (3) Apply rate limiting to prevent abuse, (4) Validate timestamp freshness (reject requests older than 5 minutes), (5) Track JWT IDs to prevent replay attacks, (6) Note that IP allowlisting is not recommended by MessageBird due to dynamic IPs, (7) Implement request logging for audit trails.
How do I test webhooks locally?
Use ngrok to create a secure HTTPS tunnel to your local server:
ngrok http 3000
. Copy the ngrok HTTPS URL and configure it in MessageBird Dashboard under Developers → Webhooks. Start your Express server and send test SMS messages. Monitor webhook deliveries in the ngrok inspector (http://localhost:4040
) and your server logs. Update the webhook URL in MessageBird Dashboard whenever ngrok restarts (free tier generates new URLs).What should I do when webhook delivery fails?
Check the webhook activity logs in MessageBird Dashboard under Developers → Webhooks → Activity. Common failures: (1) 401 Unauthorized – verify signing key matches dashboard, (2) Timeout – optimize endpoint to respond within 5 seconds, (3) Connection refused – verify endpoint URL and server status, (4) 500 errors – check application logs for exceptions. MessageBird automatically retries failed deliveries up to 10 times.
Can I use webhooks without signature verification?
No. Always implement signature verification to prevent unauthorized access and spoofed webhook requests. MessageBird provides the signing key and official SDK for verification. Skipping signature verification exposes your system to malicious actors who could send fake delivery status updates, corrupt your database, or trigger unauthorized actions. Signature verification is a security requirement, not optional.
How do I migrate from API polling to webhooks?
Replace polling logic with webhook handlers: (1) Create webhook endpoint in Express, (2) Implement signature verification middleware, (3) Configure webhook URL in MessageBird Dashboard, (4) Remove polling code that calls
messages.read()
repeatedly, (5) Update database schema to track webhook deliveries, (6) Test with ngrok for local development, (7) Deploy with HTTPS enabled. Webhooks eliminate API rate limit concerns and provide real-time updates.Summary: Building Production-Ready SMS Webhooks
You've built a complete MessageBird webhook system with Node.js and Express that tracks SMS delivery status in real time. The system includes cryptographic signature verification using HMAC-SHA256, comprehensive status code handling across three levels (status, statusReason, statusErrorCode), MongoDB persistence for audit trails, and production security with rate limiting and replay attack prevention.
Key implementation requirements:
MessageBird-Signature-JWT
headerProduction deployment checklist:
Next steps to implement this system:
npm install messagebird express body-parser mongoose dotenv ngrok redis
.env
file with MessageBird API keys from dashboardnode server.js
ngrok http 3000
Performance expectations:
Next steps for enhancement:
The webhook system provides real-time visibility into SMS delivery, eliminates polling overhead, and scales efficiently for high-volume messaging. Monitor delivery rates, optimize for carrier-specific issues, and continuously review security practices to maintain reliable SMS communications.