How to Send SMS with Node.js and Express Using MessageBird API (2025)
Step-by-step tutorial: Send SMS with Node.js, Express, and MessageBird API. Includes working code examples, async/await patterns, error handling, phone number validation, and production best practices for Node.js 22 LTS.
Learn how to send SMS with Node.js using Express and the MessageBird SMS API. This comprehensive tutorial shows you how to build a production-ready SMS application with modern async/await patterns, error handling, phone number validation, and step-by-step code examples for Node.js 22 LTS.
Important Platform Update (2024): MessageBird rebranded as "Bird" in February 2024. The legacy MessageBird API and Node.js SDK documented in this guide remain functional and supported, but Bird is transitioning to a next-generation platform. For WhatsApp integrations, ISVs must migrate to the Bird platform (app.bird.com) and enroll as a Tech Provider by March 31, 2025. SMS functionality continues to work on both platforms. See the Bird Connectivity Platform Migration Guide for details.
By the end of this tutorial, you'll have a functional Express API endpoint that accepts a recipient phone number and message body, then uses the MessageBird REST API to deliver SMS messages. This forms a fundamental building block for applications requiring notifications, alerts, or communication features.
Quick Reference: MessageBird SMS with Node.js
What You'll Build: REST API endpoint (/send-sms) for sending SMS via MessageBird
Prerequisites: Node.js 22 LTS, MessageBird account, API key, originator (VMN or Alphanumeric ID)
Time to Complete: 15–20 minutes
What is MessageBird SMS API and Why Use It?
MessageBird (now "Bird") is a cloud communications platform that provides a text messaging API for sending SMS programmatically. The MessageBird Node.js SDK simplifies integration with their REST API, letting you send transactional and marketing messages from your applications.
Why Send SMS Programmatically? Automate critical communications like order confirmations, appointment reminders, two-factor authentication codes, and real-time alerts – all without manual intervention. SMS messages have a 98% open rate compared to email's 20%, making them ideal for time-sensitive notifications.
Common SMS API Use Cases:
E-commerce: Order confirmations, shipping updates, delivery notifications
Node.js 22 LTS: JavaScript runtime enabling server-side execution. Chosen for its asynchronous nature, large ecosystem (npm), and suitability for I/O-bound tasks like API interactions. Current LTS as of October 2024, supported until April 2027.
Express.js: Minimal and flexible Node.js web application framework. Chosen for its simplicity in setting up routes and handling HTTP requests, ideal for creating REST APIs quickly.
MessageBird SDK: Official Node.js library for interacting with the MessageBird SMS gateway. Simplifies making API calls to send text messages.
dotenv: Module to load environment variables from a .env file into process.env. Securely manages sensitive information like API keys outside of the codebase.
System Architecture:
Text
+-------------+ +---------------------+ +-------------------+ +-----------------+
| User / App | ----> | Node.js/Express App | ----> | MessageBird SDK | ----> | MessageBird API | ----> SMS Network
| (makes API | POST | (Listens on /send-sms)| Calls | (Handles Auth & | HTTPS | (Processes |
| request) | | Validates input | ----> | API Interaction) | ----> | Request, Sends |
+-------------+ +---------------------+ +-------------------+ +-----------------+
| Loads API Key from .env |
+-------------------------+
Expected Outcome: A running Node.js server that exposes a /send-sms POST endpoint. Send a valid request to trigger SMS message delivery via MessageBird.
What Do You Need Before Starting?
Node.js and npm (or yarn): Install on your development machine. Recommended: Node.js 22 LTS (current LTS as of October 2024, supported until April 2027). Download from nodejs.org. Other supported LTS versions include Node.js 20 (Iron) and Node.js 18 (Hydrogen).
MessageBird Account: A free account is sufficient to start. Sign up at messagebird.com or the new bird.com platform.
MessageBird API Key: You need an API access key from your MessageBird dashboard. MessageBird provides both live and test API keys.
Live Keys: Send actual SMS messages to real phone numbers, potentially incurring costs. Use for production or real-world testing.
Test Keys: Validate API calls without sending actual SMS messages or incurring charges. Ideal during development to simulate SMS API integration without spending credits. Note: Test keys are not supported in the Conversations API (as of 2024).
MessageBird Originator: Either a purchased Virtual Mobile Number (VMN) from MessageBird or a registered Alphanumeric Sender ID (availability depends on the destination country).
Test Recipient Phone Number: A mobile phone number where you can receive the test SMS (when using a live API key).
Step 1: Set Up Your Node.js Express Project
Initialize your Node.js project and install the necessary dependencies.
Create Project Directory:
Open your terminal or command prompt and create a new directory for the project, then navigate into it.
Bash
mkdir node-messagebird-sms
cd node-messagebird-sms
Initialize Node.js Project:
Create a package.json file to manage project dependencies and scripts.
Bash
npm init -y
(The -y flag accepts default settings.)
Install Dependencies:
Install Express for the web server, the MessageBird SDK, and dotenv for environment variables.
Bash
npm install express messagebird dotenv
This downloads the packages, adds them to your node_modules directory, and lists them as dependencies in package.json.
SDK Version Note: The messagebird npm package (v4.0.1, last updated in 2021–2022) remains functional for SMS operations. While the SDK hasn't received recent updates, it continues to work with the MessageBird REST API. For the latest features and the new Bird platform, consult Bird's official documentation.
Create Project Files:
Create the main application file and the environment configuration file.
Architectural Decision: Use a single index.js file for simplicity in this basic example. In larger applications, separate concerns into different files/modules (routes, controllers, services). Using .env ensures sensitive credentials like API keys aren't hardcoded in the source code, adhering to security best practices.
Step 2: Configure MessageBird API Credentials
Securely store and access your MessageBird API key and originator information.
Navigate to the "Developers" section in the left-hand sidebar.
Click on the "API access" tab.
Find both your live and test API keys here.
If you don't have keys, click "Add access key." Choose the mode (Live or Test).
Copy the appropriate access key (use the test key for initial development, switch to the live key for sending real messages). Treat these keys like passwords – keep them confidential.
Obtain Your MessageBird Originator:
The originator is the sender ID displayed on the recipient's phone. It can be:
A Virtual Mobile Number (VMN): Purchase one in the "Numbers" section of the MessageBird Dashboard. This is the most reliable option for two-way communication and delivery to countries like the US.
An Alphanumeric Sender ID: A custom name (e.g., "My App," max 11 characters). You might need to register this via the Dashboard ("Channels" > "SMS" > "Sender IDs"). Note that Alphanumeric IDs aren't supported in all countries (e.g., the US) and can't receive replies. Check MessageBird's country restrictions documentation for details.
Choose the originator you intend to use. For VMNs, use the full number in E.164 format (e.g., +12025550184).
E.164 Format Requirement: MessageBird requires phone numbers in valid E.164 international format (country code + number, no spaces or special characters). Important: MessageBird doesn't automatically validate phone number formats. Ensure numbers are correctly formatted before submitting to the API to avoid unnecessary costs or failed deliveries. Consider using MessageBird's Lookup API for phone number validation.
Configure Environment Variables:
Open the .env file you created earlier and add your API key (start with the test key) and originator:
.env
# .env
# Start with your TEST key for development
MESSAGEBIRD_ACCESS_KEY=YOUR_TEST_API_KEY_HERE
MESSAGEBIRD_ORIGINATOR=YOUR_VMN_OR_ALPHANUMERIC_ID_HERE
Replace YOUR_TEST_API_KEY_HERE with your actual test (or live) API key.
Replace YOUR_VMN_OR_ALPHANUMERIC_ID_HERE with your chosen MessageBird number (e.g., +12025550184) or registered Alphanumeric ID (e.g., MyApp).
(Optional but Recommended) Add .env to .gitignore:
If you plan to use Git for version control, create a .gitignore file and add .env to prevent accidentally committing your credentials.
Create the file:
Linux/macOS: touch .gitignore
Windows CMD: type nul > .gitignore
Windows PowerShell: New-Item .gitignore -ItemType File
Add the following lines to .gitignore:
Text
# .gitignore
node_modules
.env
Purpose of Configuration: Using environment variables via dotenv lets the application access sensitive credentials without exposing them directly in the code. This enhances security and simplifies configuration across different deployment environments (development, staging, production). Using test keys initially prevents accidental charges and message sending during development.
Step 3: Initialize MessageBird Client with Async/Await
Write the core logic in index.js to initialize Express, load environment variables, and set up the MessageBird client using modern async/await patterns.
JavaScript
// index.js'use strict';
// 1. Load environment variablesrequire('dotenv').config();
// 2. Import dependenciesconst express = require('express');
const messagebird = require('messagebird'); // Import the main function// 3. Initialize MessageBird clientconstACCESS_KEY = process.env.MESSAGEBIRD_ACCESS_KEY;
constORIGINATOR = process.env.MESSAGEBIRD_ORIGINATOR;
if (!ACCESS_KEY || !ORIGINATOR) {
console.error('Error: MESSAGEBIRD_ACCESS_KEY and MESSAGEBIRD_ORIGINATOR must be set in the .env file.');
process.exit(1); // Exit if essential config is missing
}
// Initialize the client using the function directly with the keyconst mbClient = messagebird(ACCESS_KEY);
// 4. Initialize Express appconst app = express();
constPORT = process.env.PORT || 3000; // Use port from env or default to 3000// 5. Middleware to parse JSON request bodies
app.use(express.json());
// --- API Endpoint will be added below ---// Basic root route for testing server is up
app.get('/', (req, res) => {
res.send('SMS Sending Server is running!');
});
// 6. Start the server
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
console.log(`Using MessageBird Originator: ${ORIGINATOR}`);
// Determine if using test or live key based on key prefix (common pattern, verify if MessageBird follows this)const keyType = ACCESS_KEY.startsWith('test_') ? 'TEST' : 'LIVE';
console.log(`Using ${keyType} API Key.`);
});
Explanation:
require('dotenv').config();: Loads variables from the .env file into process.env. Call this early.
Imports the express framework and the main initialization function from the messagebird SDK.
Retrieves the API key and originator from process.env. Includes a check to ensure these critical variables are set, exiting gracefully if not. Initializes the MessageBird client by calling the imported function with the API key (messagebird(ACCESS_KEY)).
Creates an Express application instance and defines the port it listens on.
app.use(express.json());: Adds middleware to automatically parse incoming JSON request bodies, making req.body available in route handlers.
Starts the Express server, logging confirmation messages to the console, including the originator and whether a test or live key is likely being used.
Includes a simple GET / route to check if the server is running via a browser or curl.
Step 4: Create the SMS API Endpoint in Express
Create the /send-sms endpoint that handles POST requests to send messages using modern async/await syntax for asynchronous API calls.
Add the following code inside index.js, just before the app.listen call and after the app.get('/') route:
JavaScript
// index.js (continued)// --- API Endpoint ---// Use async function to allow await
app.post('/send-sms', async (req, res) => {
// 1. Extract recipient and message body from requestconst { recipient, message } = req.body;
// 2. Basic Input Validation// Note: Add more robust validation, especially for the recipient format (E.164)if (!recipient || !message) {
console.warn({ timestamp: newDate().toISOString(), level: 'WARN', message: 'Validation Error: Missing recipient or message.', requestBody: req.body });
return res.status(400).json({
status: 'error',
message: 'Recipient phone number (E.164 format) and message body are required.',
});
}
// 3. Prepare MessageBird parametersconst params = {
originator: ORIGINATOR,
recipients: [recipient], // Must be an arraybody: message,
};
console.log(`Attempting to send SMS to ${recipient} from ${ORIGINATOR}`);
try {
// 4. Send the message using MessageBird SDK with awaitconst response = await mbClient.messages.create(params);
// 5. Handle successful sending// Note: Verify the exact structure of 'response' against current SDK documentationconsole.info({ timestamp: newDate().toISOString(), level: 'INFO', message: 'MessageBird API Success', response: response, requestParams: params });
res.status(200).json({
status: 'success',
message: 'SMS submitted successfully to MessageBird!',
messageId: response.id, // Include the MessageBird message IDrecipients: response.recipients.items.map(item => ({
recipient: item.recipient,
status: item.status,
statusDatetime: item.statusDatetime,
})),
});
} catch (err) {
// 6. Handle MessageBird API errorsconsole.error({ timestamp: newDate().toISOString(), level: 'ERROR', message: 'MessageBird API Error', error: err, requestParams: params });
// Safely extract error description(s)let errorDetails = 'Unknown API error';
if (err.errors && Array.isArray(err.errors)) {
errorDetails = err.errors.map(e => e.description || 'Unknown error code').join(', ');
} elseif (err.message) {
errorDetails = err.message;
}
// Determine appropriate status code (e.g., 4xx for client errors, 5xx for server errors)// MessageBird errors often have status codes, but default to 500 if unsure.const statusCode = err.statusCode || 500;
return res.status(statusCode).json({
status: 'error',
message: `Failed to send SMS via MessageBird: ${errorDetails}`,
// DO NOT include raw error object (`err`) in production responses for security.// It's logged above for debugging.
});
}
});
// --- End of API Endpoint ---// 6. Start the server// ... (app.listen call remains here) ...
Explanation:
Endpoint Definition:app.post('/send-sms', async (req, res) => {…}) defines an async route handler for POST requests at /send-sms.
Input Extraction & Validation: Extracts recipient and message. Basic validation checks for presence. A comment reminds you to add stricter validation (e.g., E.164 format check for recipient). Returns 400 Bad Request on failure.
Parameter Preparation: Creates the params object for the SDK.
Send the Message: Uses a try…catch block for asynchronous operations. await mbClient.messages.create(params) calls the SDK function and pauses execution until the promise resolves or rejects.
Success Handling (try block): If the await succeeds, logs the success and sends a 200 OK response with relevant details from the response object (like message ID and recipient status). A comment notes that the exact response structure should be confirmed in the SDK docs.
Error Handling (catch block): If await rejects (an error occurs), the catch(err) block executes. Logs the error details for debugging, then attempts to parse a user-friendly error message from err.errors (checking it's an array) or falls back to err.message. Determines an appropriate HTTP status code (using err.statusCode if available, otherwise 500). Finally, sends the formatted error response to the client, omitting the raw err object for security.
Step 5: Implement Error Handling for SMS Delivery
The code now includes:
Configuration Errors: Checks for missing .env variables on startup.
Input Validation Errors: Returns a 400 Bad Request if recipient or message are missing.
MessageBird API Errors: Uses try…catch to handle errors from the SDK call. It logs detailed errors server-side and returns a structured, safe error message to the client with an appropriate status code.
Production Improvements:
More Specific Validation: Use a library like joi or express-validator for robust validation (e.g., checking E.164 format, message length limits). Add this validation right after extracting req.body. Critical: Since MessageBird doesn't validate phone numbers automatically, implementing strict E.164 validation prevents failed deliveries and wasted credits.
Phone Number Validation Service: Integrate MessageBird's Lookup API to validate phone numbers before sending. This verifies the number is valid, active, and routable, reducing delivery failures.
Structured Logging: Replace console.log/warn/info/error with a dedicated logging library (like winston or pino) for structured JSON logs, controllable log levels, and outputting to files or services.
Error Tracking Services: Integrate services like Sentry or Bugsnag to automatically capture and report errors.
Security Headers: Use middleware like helmet to set various HTTP headers for security.
Rate Limiting: Implement rate limiting on the endpoint (e.g., using express-rate-limit) to prevent abuse.
Retry Mechanisms: For transient network errors or specific MessageBird errors (like rate limits), implement a retry strategy with exponential backoff. Be cautious not to cause duplicate messages.
Example of adding E.164 format validation:
JavaScript
// Inside /send-sms route, after extracting recipientconst e164Regex = /^\+[1-9]\d{1,14}$/; // Basic E.164 regex (ITU-T E.164 standard)if (!recipient || !message || !e164Regex.test(recipient)) {
console.warn('Validation Error: Invalid input.', { recipient, message });
return res.status(400).json({
status: 'error',
message: 'Recipient phone number (must be valid E.164 format like +1234567890) and message body are required.',
});
}
Step 6: Test Your SMS Endpoint with cURL
Run the server and test the endpoint using curl.
Run the Application:
Open your terminal in the project directory (node-messagebird-sms/) and run:
Bash
node index.js
You should see output:
Text
Server running on http://localhost:3000
Using MessageBird Originator: YOUR_VMN_OR_ALPHANUMERIC_ID_HERE
Using TEST API Key. // Or LIVE depending on your .env
Send a Test SMS using curl:
Open another terminal window. Replace +1xxxxxxxxxx with your actual recipient phone number (in E.164 format) and modify the message text if desired.
Bash
curl -X POST http://localhost:3000/send-sms \
-H "Content-Type: application/json" \
-d '{
"recipient": "+1xxxxxxxxxx",
"message": "Hello from Node.js and MessageBird! Sent on Jan 10, 2024."
}'
Check the Results:
Terminal 1 (Server Logs): Check log output indicating the attempt and the success or failure response from MessageBird.
Success Example (Test Key): You'll see a success log, but no SMS is actually sent.
Success Example (Live Key): You'll see a success log, and an SMS should arrive.
Text
Attempting to send SMS to +1xxxxxxxxxx from YOUR_ORIGINATOR
{"timestamp":"...","level":"INFO","message":"MessageBird API Success", … }
Error Example (e.g., invalid recipient):
Text
Attempting to send SMS to +1invalidnumber from YOUR_ORIGINATOR
{"timestamp":"...","level":"ERROR","message":"MessageBird API Error", … errors: [ { code: 21, description: 'Invalid recipient.', parameter: 'recipients' } ] …}
Terminal 2 (curl Output):
Success:
JSON
{"status":"success","message":"SMS submitted successfully to MessageBird!","messageId":"mb_message_id_string","recipients":[{"recipient":1xxxxxxxxxx,"status":"sent","statusDatetime":"…"}]}
Input Validation Error (missing field or invalid format):
JSON
{"status":"error","message":"Recipient phone number (must be valid E.164 format like +1234567890) and message body are required."}
MessageBird API Error (e.g., bad key):json { "status": "error", "message": "Failed to send SMS via MessageBird: Authentication failed" }
Recipient Phone: If using a live API key and the call was successful, receive the SMS on the specified recipient phone within a few seconds. If using a test key, no SMS arrives.
Troubleshooting Common SMS Integration Issues
Error: MESSAGEBIRD_ACCESS_KEY… must be set: Ensure your .env file exists in the project root, is correctly named (.env), and contains the MESSAGEBIRD_ACCESS_KEY and MESSAGEBIRD_ORIGINATOR variables with valid values. Restart the Node.js server after editing .env.
400 Bad Request Response: Verify curl has -H "Content-Type: application/json" and the -d payload is valid JSON with recipient (in E.164 format) and message. Check server logs for validation errors.
401, 403, or 500 Error with "Authentication failed", "Invalid Signature", or similar:
Your MESSAGEBIRD_ACCESS_KEY in .env is incorrect. Verify it in the MessageBird Dashboard.
You're using a test key for an operation requiring a live key, or vice-versa. Note that test keys don't work with the Conversations API (as of 2024). Ensure you're using the correct key type for your needs. Double-check the copied key value.
Error with "Invalid originator": The MESSAGEBIRD_ORIGINATOR in .env is incorrect, not registered, or not permitted for the destination country (especially Alphanumeric IDs). Check format (E.164 for numbers) and status in the MessageBird Dashboard. See MessageBird's Originator article.
Error with "Invalid recipient" or "Number not routable": The recipient number is invalid, not in E.164 format (+ country code + number), or for a destination MessageBird can't reach. Remember: MessageBird doesn't validate phone numbers automatically – ensure proper E.164 formatting before submission to avoid costs from invalid numbers.
Error with "Insufficient balance": Your MessageBird account needs credits (only applies when using a live key). Add funds via the Dashboard.
SMS Not Received Despite Success Response (Live Key):
Verify the recipient number is in valid E.164 format.
Wait a few minutes (carrier delays).
Check MessageBird Dashboard logs ("SMS" > "SMS Overview") for detailed delivery status (e.g., carrier rejection).
Ensure the phone has signal and isn't blocking unknown senders.
Alphanumeric IDs might not be supported by the destination carrier (e.g., US/Canada often require local numbers). Try a VMN.
Rate Limiting: High volume sending might hit MessageBird rate limits. Implement queuing and backoff strategies.
SDK Response Structure: Verify the exact structure of the success (response) and error (err) objects from mbClient.messages.create against the current official MessageBird Node.js SDK documentation, as it can change over time.
Platform Migration: If you're building new WhatsApp integrations or planning long-term projects, review Bird's migration documentation to understand the transition from MessageBird to Bird platforms.
Running Your Node.js SMS Application
To run the application, navigate to the project directory in your terminal and execute:
Bash
node index.js
The server starts and remains running until you stop it (usually with Ctrl + C).
Frequently Asked Questions
What is the difference between MessageBird test and live API keys?
Test keys validate your API integration without sending actual SMS messages or incurring charges. They're ideal for development and testing. Live keys send real SMS messages to phone numbers and consume account credits. Note that test keys don't work with the Conversations API as of 2024.
How do you format phone numbers for MessageBird SMS API?
MessageBird requires phone numbers in E.164 international format: a plus sign (+) followed by the country code and subscriber number (1–15 digits total). Example: +12025550184 for a US number. Remove all spaces, dashes, and parentheses. Important: MessageBird doesn't validate formats automatically – you must validate before submission.
What Node.js version should you use with MessageBird?
Use Node.js 22 LTS (recommended as of October 2024, supported until April 2027). Other supported LTS versions include Node.js 20 (Iron) and Node.js 18 (Hydrogen). The MessageBird SDK (v4.0.1) works with all current LTS versions.
How do you handle MessageBird API errors in Node.js?
Use try…catch with async/await to handle errors. Extract error details from err.errors array or err.message. Return appropriate HTTP status codes (400 for client errors, 500 for server errors). Log detailed errors server-side but return safe, user-friendly messages to clients. Never expose raw error objects in production responses.
Can you use MessageBird with Express.js async/await?
Yes. Define route handlers as async functions and use await with mbClient.messages.create(). Wrap in try…catch for error handling. This modern pattern is cleaner than callback or promise chains and is the recommended approach for Node.js API development.
What is the MessageBird originator and why does it matter?
The originator is the sender ID displayed on the recipient's phone. It can be a Virtual Mobile Number (VMN) purchased from MessageBird or an Alphanumeric Sender ID (custom name, max 11 characters). VMNs work globally and enable two-way communication. Alphanumeric IDs aren't supported in all countries (e.g., US) and can't receive replies.
Conclusion and Next Steps
You've successfully built a Node.js Express application capable of sending SMS messages using the MessageBird API and modern JavaScript practices. You learned how to set up a project, manage API keys (test vs. live), create an API endpoint using async/await, interact with the MessageBird SDK, and handle errors securely.
Next Steps & Potential Improvements:
Robust Input Validation: Implement stricter validation (E.164 format, message length) using libraries like joi or express-validator. Consider integrating MessageBird's Lookup API for real-time phone number validation.
User Interface: Build a front-end to interact with your SMS API.
Asynchronous Processing: Use a message queue (e.g., RabbitMQ, Redis/BullMQ) for high-volume sending to improve responsiveness and manage retries.
Database Integration: Store message logs or application data.
Deployment: Deploy to a hosting provider (Heroku, AWS, etc.) using Docker and CI/CD.
Monitoring & Alerting: Integrate monitoring (Prometheus/Grafana, Datadog) for performance and error tracking.
Platform Migration Planning: For new projects or long-term implementations, evaluate migrating to the Bird platform for access to latest features and pricing benefits (90% SMS discount as of February 2024).
Code Repository
[Actual repository link should be inserted here if available]
This foundation enables you to integrate powerful SMS capabilities into your Node.js applications. Happy coding!
You can send SMS messages programmatically using Node.js, Express, and the MessageBird API. Set up an Express server, install the MessageBird SDK, configure your API key, and create a POST endpoint that handles sending messages via the API based on user input from the request body.
MessageBird is a communications platform with an API and Node.js SDK that simplifies sending SMS messages, making it ideal for applications needing notifications, alerts, and other communication features. You use their Node SDK to interface with the API.
Express.js simplifies the creation of routes and handling of HTTP requests, making it ideal for quickly creating APIs. Its minimalist framework enhances the Node server for easily sending SMS messages.
Create a '.env' file in your project's root directory. Add your MessageBird API key (test or live) and originator (VMN or Alphanumeric Sender ID) as environment variables like MESSAGEBIRD_ACCESS_KEY=your_key. Load these variables into your Node.js application using the dotenv package.
The originator is the sender ID displayed on the recipient's phone. It can be a Virtual Mobile Number (VMN) or a registered Alphanumeric Sender ID. The originator is configured in your application's environment variables and included with each message sent through the API.
Create a POST route in your Express app (e.g., '/send-sms'). Extract the recipient's number and message body from the request using req.body. Validate inputs and format them for the messagebird.messages.create function of the MessageBird SDK using parameters such as recipient, body, and originator. Return success or error responses from the endpoint accordingly.
Wrap your MessageBird API calls in a try...catch block to handle errors gracefully. Log error details on the server-side and return informative but safe error messages to the client, ensuring sensitive information is not exposed. Utilize the statusCode property of MessageBird errors when determining an appropriate HTTP response code.
Use the MessageBird test API key for development and testing purposes to avoid real SMS costs. When your application is ready for production, switch to the live key to send actual SMS messages. Test keys simulate API interaction without actually delivering real messages.
Use a regex to check for valid E.164 number format (+ followed by country code and up to 14 digits) for recipient phone numbers to minimize invalid requests. You can also use libraries like joi or express-validator for more comprehensive input validation and security.
Next steps include implementing robust input validation using libraries like joi, building a front-end UI for interaction, and integrating asynchronous message queuing with a service like RabbitMQ or Redis. Additional improvements could be database integration and implementing security measures like rate limiting, API authentication, and helmet.
Double-check that your MESSAGEBIRD_ACCESS_KEY in the .env file is correct and matches the key from your MessageBird dashboard. Ensure you are using the appropriate key type (test or live) for the intended operation. Restart the server after any .env changes.
The 'Invalid originator' error usually means your MESSAGEBIRD_ORIGINATOR value in the .env file is incorrect, not registered, or prohibited for the destination country. Verify its format (E.164 for numbers) and check its status on the MessageBird dashboard.
If using a live key and receiving a success response but no SMS arrives, double-check the recipient number, wait a few minutes for potential carrier delays, examine MessageBird dashboard logs for detailed delivery statuses, and confirm that the phone has network signal and is not blocking messages.
For high-volume SMS sending, use asynchronous processing and message queues like RabbitMQ or Redis to improve server responsiveness and manage retries. Implement proper error handling and logging, as well as rate limiting with packages like express-rate-limit and use enhanced security measures to prevent abuse.
Learn how to send SMS with Node.js using Express and the MessageBird SMS API. This comprehensive tutorial shows you how to build a production-ready SMS application with modern async/await patterns, error handling, phone number validation, and step-by-step code examples for Node.js 22 LTS.
By the end of this tutorial, you'll have a functional Express API endpoint that accepts a recipient phone number and message body, then uses the MessageBird REST API to deliver SMS messages. This forms a fundamental building block for applications requiring notifications, alerts, or communication features.
Quick Reference: MessageBird SMS with Node.js
What You'll Build: REST API endpoint (
/send-sms) for sending SMS via MessageBirdTechnologies: Node.js 22 LTS, Express.js, MessageBird SDK v4.0.1, dotenv
Key Concepts:
Prerequisites: Node.js 22 LTS, MessageBird account, API key, originator (VMN or Alphanumeric ID)
Time to Complete: 15–20 minutes
What is MessageBird SMS API and Why Use It?
MessageBird (now "Bird") is a cloud communications platform that provides a text messaging API for sending SMS programmatically. The MessageBird Node.js SDK simplifies integration with their REST API, letting you send transactional and marketing messages from your applications.
Why Send SMS Programmatically? Automate critical communications like order confirmations, appointment reminders, two-factor authentication codes, and real-time alerts – all without manual intervention. SMS messages have a 98% open rate compared to email's 20%, making them ideal for time-sensitive notifications.
Common SMS API Use Cases:
What Technologies Does This Tutorial Use?
.envfile intoprocess.env. Securely manages sensitive information like API keys outside of the codebase.System Architecture:
Expected Outcome: A running Node.js server that exposes a
/send-smsPOST endpoint. Send a valid request to trigger SMS message delivery via MessageBird.What Do You Need Before Starting?
Step 1: Set Up Your Node.js Express Project
Initialize your Node.js project and install the necessary dependencies.
Create Project Directory: Open your terminal or command prompt and create a new directory for the project, then navigate into it.
mkdir node-messagebird-sms cd node-messagebird-smsInitialize Node.js Project: Create a
package.jsonfile to manage project dependencies and scripts.(The
-yflag accepts default settings.)Install Dependencies: Install Express for the web server, the MessageBird SDK, and dotenv for environment variables.
This downloads the packages, adds them to your
node_modulesdirectory, and lists them as dependencies inpackage.json.SDK Version Note: The
messagebirdnpm package (v4.0.1, last updated in 2021–2022) remains functional for SMS operations. While the SDK hasn't received recent updates, it continues to work with the MessageBird REST API. For the latest features and the new Bird platform, consult Bird's official documentation.Create Project Files: Create the main application file and the environment configuration file.
touch index.js .envtype nul > index.js type nul > .envYour basic project structure should now look like this:
Architectural Decision: Use a single
index.jsfile for simplicity in this basic example. In larger applications, separate concerns into different files/modules (routes, controllers, services). Using.envensures sensitive credentials like API keys aren't hardcoded in the source code, adhering to security best practices.Step 2: Configure MessageBird API Credentials
Securely store and access your MessageBird API key and originator information.
Obtain Your MessageBird API Key:
Obtain Your MessageBird Originator:
originatoris the sender ID displayed on the recipient's phone. It can be:+12025550184).Configure Environment Variables: Open the
.envfile you created earlier and add your API key (start with the test key) and originator:YOUR_TEST_API_KEY_HEREwith your actual test (or live) API key.YOUR_VMN_OR_ALPHANUMERIC_ID_HEREwith your chosen MessageBird number (e.g.,+12025550184) or registered Alphanumeric ID (e.g.,MyApp).(Optional but Recommended) Add
.envto.gitignore: If you plan to use Git for version control, create a.gitignorefile and add.envto prevent accidentally committing your credentials.touch .gitignoretype nul > .gitignoreNew-Item .gitignore -ItemType File.gitignore:Purpose of Configuration: Using environment variables via
dotenvlets the application access sensitive credentials without exposing them directly in the code. This enhances security and simplifies configuration across different deployment environments (development, staging, production). Using test keys initially prevents accidental charges and message sending during development.Step 3: Initialize MessageBird Client with Async/Await
Write the core logic in
index.jsto initialize Express, load environment variables, and set up the MessageBird client using modern async/await patterns.// index.js 'use strict'; // 1. Load environment variables require('dotenv').config(); // 2. Import dependencies const express = require('express'); const messagebird = require('messagebird'); // Import the main function // 3. Initialize MessageBird client const ACCESS_KEY = process.env.MESSAGEBIRD_ACCESS_KEY; const ORIGINATOR = process.env.MESSAGEBIRD_ORIGINATOR; if (!ACCESS_KEY || !ORIGINATOR) { console.error('Error: MESSAGEBIRD_ACCESS_KEY and MESSAGEBIRD_ORIGINATOR must be set in the .env file.'); process.exit(1); // Exit if essential config is missing } // Initialize the client using the function directly with the key const mbClient = messagebird(ACCESS_KEY); // 4. Initialize Express app const app = express(); const PORT = process.env.PORT || 3000; // Use port from env or default to 3000 // 5. Middleware to parse JSON request bodies app.use(express.json()); // --- API Endpoint will be added below --- // Basic root route for testing server is up app.get('/', (req, res) => { res.send('SMS Sending Server is running!'); }); // 6. Start the server app.listen(PORT, () => { console.log(`Server running on http://localhost:${PORT}`); console.log(`Using MessageBird Originator: ${ORIGINATOR}`); // Determine if using test or live key based on key prefix (common pattern, verify if MessageBird follows this) const keyType = ACCESS_KEY.startsWith('test_') ? 'TEST' : 'LIVE'; console.log(`Using ${keyType} API Key.`); });Explanation:
require('dotenv').config();: Loads variables from the.envfile intoprocess.env. Call this early.expressframework and the main initialization function from themessagebirdSDK.process.env. Includes a check to ensure these critical variables are set, exiting gracefully if not. Initializes the MessageBird client by calling the imported function with the API key (messagebird(ACCESS_KEY)).app.use(express.json());: Adds middleware to automatically parse incoming JSON request bodies, makingreq.bodyavailable in route handlers./route to check if the server is running via a browser orcurl.Step 4: Create the SMS API Endpoint in Express
Create the
/send-smsendpoint that handles POST requests to send messages using modern async/await syntax for asynchronous API calls.Add the following code inside
index.js, just before theapp.listencall and after theapp.get('/')route:// index.js (continued) // --- API Endpoint --- // Use async function to allow await app.post('/send-sms', async (req, res) => { // 1. Extract recipient and message body from request const { recipient, message } = req.body; // 2. Basic Input Validation // Note: Add more robust validation, especially for the recipient format (E.164) if (!recipient || !message) { console.warn({ timestamp: new Date().toISOString(), level: 'WARN', message: 'Validation Error: Missing recipient or message.', requestBody: req.body }); return res.status(400).json({ status: 'error', message: 'Recipient phone number (E.164 format) and message body are required.', }); } // 3. Prepare MessageBird parameters const params = { originator: ORIGINATOR, recipients: [recipient], // Must be an array body: message, }; console.log(`Attempting to send SMS to ${recipient} from ${ORIGINATOR}`); try { // 4. Send the message using MessageBird SDK with await const response = await mbClient.messages.create(params); // 5. Handle successful sending // Note: Verify the exact structure of 'response' against current SDK documentation console.info({ timestamp: new Date().toISOString(), level: 'INFO', message: 'MessageBird API Success', response: response, requestParams: params }); res.status(200).json({ status: 'success', message: 'SMS submitted successfully to MessageBird!', messageId: response.id, // Include the MessageBird message ID recipients: response.recipients.items.map(item => ({ recipient: item.recipient, status: item.status, statusDatetime: item.statusDatetime, })), }); } catch (err) { // 6. Handle MessageBird API errors console.error({ timestamp: new Date().toISOString(), level: 'ERROR', message: 'MessageBird API Error', error: err, requestParams: params }); // Safely extract error description(s) let errorDetails = 'Unknown API error'; if (err.errors && Array.isArray(err.errors)) { errorDetails = err.errors.map(e => e.description || 'Unknown error code').join(', '); } else if (err.message) { errorDetails = err.message; } // Determine appropriate status code (e.g., 4xx for client errors, 5xx for server errors) // MessageBird errors often have status codes, but default to 500 if unsure. const statusCode = err.statusCode || 500; return res.status(statusCode).json({ status: 'error', message: `Failed to send SMS via MessageBird: ${errorDetails}`, // DO NOT include raw error object (`err`) in production responses for security. // It's logged above for debugging. }); } }); // --- End of API Endpoint --- // 6. Start the server // ... (app.listen call remains here) ...Explanation:
app.post('/send-sms', async (req, res) => {…})defines anasyncroute handler for POST requests at/send-sms.recipientandmessage. Basic validation checks for presence. A comment reminds you to add stricter validation (e.g., E.164 format check forrecipient). Returns400 Bad Requeston failure.paramsobject for the SDK.try…catchblock for asynchronous operations.await mbClient.messages.create(params)calls the SDK function and pauses execution until the promise resolves or rejects.awaitsucceeds, logs the success and sends a200 OKresponse with relevant details from theresponseobject (like message ID and recipient status). A comment notes that the exactresponsestructure should be confirmed in the SDK docs.awaitrejects (an error occurs), thecatch(err)block executes. Logs the error details for debugging, then attempts to parse a user-friendly error message fromerr.errors(checking it's an array) or falls back toerr.message. Determines an appropriate HTTP status code (usingerr.statusCodeif available, otherwise500). Finally, sends the formatted error response to the client, omitting the rawerrobject for security.Step 5: Implement Error Handling for SMS Delivery
The code now includes:
.envvariables on startup.400 Bad Requestifrecipientormessageare missing.try…catchto handle errors from the SDK call. It logs detailed errors server-side and returns a structured, safe error message to the client with an appropriate status code.Production Improvements:
joiorexpress-validatorfor robust validation (e.g., checking E.164 format, message length limits). Add this validation right after extractingreq.body. Critical: Since MessageBird doesn't validate phone numbers automatically, implementing strict E.164 validation prevents failed deliveries and wasted credits.console.log/warn/info/errorwith a dedicated logging library (likewinstonorpino) for structured JSON logs, controllable log levels, and outputting to files or services.helmetto set various HTTP headers for security.express-rate-limit) to prevent abuse.Example of adding E.164 format validation:
// Inside /send-sms route, after extracting recipient const e164Regex = /^\+[1-9]\d{1,14}$/; // Basic E.164 regex (ITU-T E.164 standard) if (!recipient || !message || !e164Regex.test(recipient)) { console.warn('Validation Error: Invalid input.', { recipient, message }); return res.status(400).json({ status: 'error', message: 'Recipient phone number (must be valid E.164 format like +1234567890) and message body are required.', }); }Step 6: Test Your SMS Endpoint with cURL
Run the server and test the endpoint using
curl.Run the Application: Open your terminal in the project directory (
node-messagebird-sms/) and run:You should see output:
Send a Test SMS using
curl: Open another terminal window. Replace+1xxxxxxxxxxwith your actual recipient phone number (in E.164 format) and modify the message text if desired.curl -X POST http://localhost:3000/send-sms \ -H "Content-Type: application/json" \ -d '{ "recipient": "+1xxxxxxxxxx", "message": "Hello from Node.js and MessageBird! Sent on Jan 10, 2024." }'Check the Results:
curlOutput):{ "status": "success", "message": "SMS submitted successfully to MessageBird!", "messageId": "mb_message_id_string", "recipients": [ { "recipient": 1xxxxxxxxxx, "status": "sent", "statusDatetime": "…" } ] }{ "status": "error", "message": "Recipient phone number (must be valid E.164 format like +1234567890) and message body are required." }json { "status": "error", "message": "Failed to send SMS via MessageBird: Authentication failed" }Troubleshooting Common SMS Integration Issues
Error: MESSAGEBIRD_ACCESS_KEY… must be set: Ensure your.envfile exists in the project root, is correctly named (.env), and contains theMESSAGEBIRD_ACCESS_KEYandMESSAGEBIRD_ORIGINATORvariables with valid values. Restart the Node.js server after editing.env.400 Bad RequestResponse: Verifycurlhas-H "Content-Type: application/json"and the-dpayload is valid JSON withrecipient(in E.164 format) andmessage. Check server logs for validation errors.401,403, or500Error with "Authentication failed", "Invalid Signature", or similar:MESSAGEBIRD_ACCESS_KEYin.envis incorrect. Verify it in the MessageBird Dashboard.MESSAGEBIRD_ORIGINATORin.envis incorrect, not registered, or not permitted for the destination country (especially Alphanumeric IDs). Check format (E.164 for numbers) and status in the MessageBird Dashboard. See MessageBird's Originator article.recipientnumber is invalid, not in E.164 format (+country code + number), or for a destination MessageBird can't reach. Remember: MessageBird doesn't validate phone numbers automatically – ensure proper E.164 formatting before submission to avoid costs from invalid numbers.response) and error (err) objects frommbClient.messages.createagainst the current official MessageBird Node.js SDK documentation, as it can change over time.Running Your Node.js SMS Application
To run the application, navigate to the project directory in your terminal and execute:
The server starts and remains running until you stop it (usually with
Ctrl + C).Frequently Asked Questions
What is the difference between MessageBird test and live API keys?
Test keys validate your API integration without sending actual SMS messages or incurring charges. They're ideal for development and testing. Live keys send real SMS messages to phone numbers and consume account credits. Note that test keys don't work with the Conversations API as of 2024.
How do you format phone numbers for MessageBird SMS API?
MessageBird requires phone numbers in E.164 international format: a plus sign (+) followed by the country code and subscriber number (1–15 digits total). Example:
+12025550184for a US number. Remove all spaces, dashes, and parentheses. Important: MessageBird doesn't validate formats automatically – you must validate before submission.What Node.js version should you use with MessageBird?
Use Node.js 22 LTS (recommended as of October 2024, supported until April 2027). Other supported LTS versions include Node.js 20 (Iron) and Node.js 18 (Hydrogen). The MessageBird SDK (v4.0.1) works with all current LTS versions.
How do you handle MessageBird API errors in Node.js?
Use
try…catchwithasync/awaitto handle errors. Extract error details fromerr.errorsarray orerr.message. Return appropriate HTTP status codes (400 for client errors, 500 for server errors). Log detailed errors server-side but return safe, user-friendly messages to clients. Never expose raw error objects in production responses.Can you use MessageBird with Express.js async/await?
Yes. Define route handlers as
asyncfunctions and useawaitwithmbClient.messages.create(). Wrap intry…catchfor error handling. This modern pattern is cleaner than callback or promise chains and is the recommended approach for Node.js API development.What is the MessageBird originator and why does it matter?
The originator is the sender ID displayed on the recipient's phone. It can be a Virtual Mobile Number (VMN) purchased from MessageBird or an Alphanumeric Sender ID (custom name, max 11 characters). VMNs work globally and enable two-way communication. Alphanumeric IDs aren't supported in all countries (e.g., US) and can't receive replies.
Conclusion and Next Steps
You've successfully built a Node.js Express application capable of sending SMS messages using the MessageBird API and modern JavaScript practices. You learned how to set up a project, manage API keys (test vs. live), create an API endpoint using async/await, interact with the MessageBird SDK, and handle errors securely.
Next Steps & Potential Improvements:
joiorexpress-validator. Consider integrating MessageBird's Lookup API for real-time phone number validation.express-rate-limit), security headers (helmet).Code Repository
[Actual repository link should be inserted here if available]
This foundation enables you to integrate powerful SMS capabilities into your Node.js applications. Happy coding!
Sources: