Frequently Asked Questions
Use the MessageBird API and Node.js SDK along with the Express framework. Create a POST endpoint in your Express app that takes the recipient's number and message. Then, initialize the MessageBird client with your API key and use the messagebird.messages.create()
method to send the SMS.
MessageBird is a communications platform that provides a simple way to send SMS messages programmatically. Its Node.js SDK simplifies the process of integrating SMS sending capabilities into Node.js and Express applications.
Dotenv helps manage environment variables securely. It loads credentials from a .env
file, keeping sensitive information like your MessageBird API key separate from your codebase and out of version control for improved security.
Alphanumeric sender IDs (e.g., 'MyApp') can be used as the message sender, but check MessageBird's documentation for country restrictions, as they're not universally supported. Note that recipients cannot reply to alphanumeric IDs.
No, test API keys only simulate message sending for testing purposes. You need a live API key from your MessageBird Dashboard to actually deliver SMS messages to real recipients. This requires a purchased number.
Open your terminal in your project directory and run npm install messagebird dotenv express
. This installs the necessary MessageBird Node.js SDK, dotenv, and Express packages for your project.
The express.json()
middleware enables your Express server to parse incoming JSON data in the request body. This is crucial for retrieving the recipient's number and message text from POST requests sent to the /send-sms endpoint.
The MessageBird SDK provides an error object in the callback function if the API call fails. Check for the err
object and log the error details using console.error
. Return a 500 Internal Server Error response with details from the error object if available.
Adding the .env
file to .gitignore
prevents it from being committed to version control (like Git). This is crucial for security, as it protects sensitive credentials like your MessageBird API key from being exposed publicly in online repositories.
In your MessageBird Dashboard, navigate to the 'Developers' section and then to 'Webhooks.' Create a new webhook and point it to a designated endpoint in your Express application to receive and process incoming SMS messages.
Standard SMS messages (GSM-7) have a 160-character limit. Using characters outside GSM-7 (like emojis) reduces the limit to 70 characters (UCS-2 encoding). Longer messages are split into multiple parts, potentially increasing costs.
Implement webhooks in your MessageBird account settings to receive Delivery Reports (DLRs). MessageBird will send notifications to your specified webhook URL when the status of a sent SMS message changes (e.g., delivered, failed).
Double-check your MessageBird API key in the .env
file and verify it matches the active key in your MessageBird Dashboard. Ensure you are using the correct key type (live or test) as well.
Explore additional MessageBird features like receiving SMS, checking delivery status (DLRs), sending MMS, and more. Enhance security by implementing API authentication and rate limiting. Integrate the service into your larger applications for sending notifications.
MessageBird Node.js Express Tutorial: Build Two-Way SMS with Webhooks (2024-2025)
Build a Node.js application using Express to send and receive SMS messages via the MessageBird API (now branded as Bird). This comprehensive tutorial covers implementing two-way SMS messaging with webhooks, including project setup, MessageBird SDK configuration, outbound SMS sending, inbound SMS webhook receivers, error handling, and testing.
Important Note (February 2024): MessageBird rebranded as "Bird" in February 2024 with significant price reductions. The legacy MessageBird API (used in this guide) continues to be supported but no longer accepts new customers. New integrations should use the Bird API (docs.bird.com), though the concepts and patterns for two-way SMS messaging remain similar.
By the end of this tutorial, you'll have a functional Express server with REST API endpoints for both sending SMS messages and receiving inbound SMS via webhooks – enabling true bidirectional communication for customer support, notifications, and interactive messaging.
What You'll Build: Two-Way SMS Application Overview
Goal: Create a backend service that programmatically sends and receives SMS messages for two-way communication using MessageBird's Node.js SDK.
Problem Solved: Integrate bidirectional SMS capabilities into larger applications for notifications, alerts, customer support, surveys, or interactive communication without complex infrastructure.
Technologies Used:
.env
intoprocess.env
. Securely manages sensitive information like API keys outside your codebase.Prerequisites:
Final Outcome: A running Express server with:
POST /send-sms
endpoint that sends SMS messages using MessageBird APIPOST /webhook/inbound-sms
endpoint that receives and processes incoming SMS messages1. Set Up the Node.js Project
Initialize your Node.js project and install dependencies.
Create Project Directory: Open your terminal and create a directory:
Initialize Node.js Project: Create
package.json
:The
-y
flag accepts default settings.Install Dependencies: Install Express, MessageBird SDK, and dotenv:
express
– Web frameworkmessagebird
– SDK for MessageBird APIdotenv
– Loads environment variables from.env
Create Project Files:
index.js
– Express server and API logic.env
– Sensitive credentials (MessageBird API key). Never commit to version control..gitignore
– Specifies untracked files Git should ignoreConfigure
.gitignore
: Open.gitignore
and add:Keeping
.env
out of Git is crucial for security.node_modules
can be regenerated withnpm install
.Project Structure: Your directory should look like this:
2. Configure MessageBird API Credentials
Configure your application to use MessageBird credentials securely.
Obtain MessageBird API Key:
Purchase a Virtual Number for Two-Way SMS:
SMS messages need a sender ("originator"). For two-way messaging:
Choose a purchased number for full two-way messaging capabilities.
Understanding MessageBird Rate Limits (US/Canada): American and Canadian numbers have:
Configure Environment Variables: Open
.env
and add your credentials:YOUR_LIVE_API_KEY_HERE
with your copied keyYOUR_PURCHASED_NUMBER_OR_SENDER_ID
with your virtual number (international format:+12005550100
) or alphanumeric sender ID.env
separates them from code – more secure and easier to manage across environments3. How to Send SMS Messages: Build the Outbound API Endpoint
Build the Express server and API endpoint for sending SMS messages with MessageBird.
Set Up Express Server: Open
index.js
and add:Key Points:
require('dotenv').config()
– Loads.env
variables. Must be called early.initClient(...)
– Initializes MessageBird SDK with your API keyexpress()
– Creates Express applicationapp.use(express.json())
– Parses incoming JSON payloads. Crucial for API endpoint.Create SMS Sending Endpoint: Add the
POST /send-sms
route inindex.js
belowapp.use(express.json())
and beforeapp.listen()
:Key Points:
app.post('/send-sms', ...)
– Listens for POST requests at/send-sms
req.body
– Parsed JSON payload (viaexpress.json()
middleware)params
– Data for MessageBird API call.recipients
must be array.messagebird.messages.create(params, callback)
– Asynchronous SDK callcallback(err, response)
– Executes when MessageBird respondsif (err)
– API call failed. Log error, return 500 Internal Server Error with description.else
– Success. Log response, return 200 OK with message ID and recipient count..then().catch()
) andasync/await
4. Add Error Handling and Logging
Basic error handling is already in the
/send-sms
route:recipient
ormessage
. Returns 400 Bad Request.err
object from MessageBird callback. Logs withconsole.error
, returns 500 with details.console.log
for informational messages,console.error
for errors.Production Enhancements:
joi
orexpress-validator
for complex validation (e.g., E.164 phone number format)winston
orpino
for structured JSON logs, log levels, and external logging services (Datadog, Loggly)async-retry
with exponential backoff) – critical for important notifications5. Implement Security Best Practices
Basic security is in place, but consider:
dotenv
) and.gitignore
keeps keys out of version control. Set restricted permissions on server (e.g.,chmod 600 .env
).recipient
andmessage
checks.message
content elsewhere, sanitize to prevent Cross-Site Scripting (XSS) – usedompurify
for HTML rendering or ensure proper database escaping.express-rate-limit
middleware. Restrict requests per IP/user within time windows (e.g., 10 requests/minute). Controls costs and prevents spamming.6. Understanding SMS Character Limits and Encoding
+14155552671
).7. How to Receive SMS Messages: Implement Inbound Webhooks
Enable two-way messaging by configuring MessageBird to forward incoming SMS to your application via webhooks.
Set Up Webhook Endpoint for Inbound SMS
Create Inbound SMS Handler: Add this route in
index.js
beforeapp.listen()
:Key Points:
express.urlencoded()
middlewareoriginator
= sender's number,recipient
= your MessageBird numberConfigure MessageBird Flow Builder for Webhooks
Configure Webhook in MessageBird Dashboard:
Important: Webhook URLs cannot be set via API – you must use Flow Builder in the MessageBird dashboard.
a. Expose Local Server for Testing:
Copy the HTTPS forwarding URL (e.g.,
https://abc123.ngrok.io
)b. Set Up Flow Builder for Webhook Routing:
https://abc123.ngrok.io/webhook/inbound-sms
)Webhook Payload Structure
MessageBird sends form-encoded fields:
Production Webhook Security
Implement signature verification for production:
8. Testing Your Two-Way SMS Application
Start the Server: Open your terminal in the project directory and run:
You should see
Server listening on port 3000
.Test Outbound SMS with
curl
: Open another terminal window and usecurl
(or a tool like Postman/Insomnia) to send a POST request to your endpoint. ReplaceYOUR_RECIPIENT_PHONE_NUMBER
with a real phone number (in international format, e.g.,+14155552671
) you can check.Test Inbound SMS (Two-Way Messaging):
a. Ensure your server is running and ngrok is active (if testing locally) b. Ensure Flow Builder is configured with your webhook URL c. Send an SMS from your phone to your MessageBird virtual number d. Check your server logs – you should see the webhook payload e. If auto-reply is enabled, check your phone for the response
9. Common Issues and Troubleshooting
FATAL ERROR: MESSAGEBIRD_API_KEY environment variable is not set.
.env
file is missing, not named correctly (.env
), not located in the root directory wherenode index.js
is executed, or theMESSAGEBIRD_API_KEY
line is missing/commented out. Therequire('dotenv').config();
call might be missing or placed after the variable is accessed..env
file's presence, name, location, and content. Ensurerequire('dotenv').config();
is at the very top ofindex.js
.Authentication failed
(from MessageBird API Response)MESSAGEBIRD_API_KEY
in your.env
file is incorrect, has been revoked, or is a test key being used when a live key is required (or vice-versa)..env
file against the active key in your MessageBird Dashboard (Developers -> API access). Ensure you are using the correct type of key (live vs. test).message submission failed, invalid originator
/Originator not allowed
MESSAGEBIRD_ORIGINATOR
specified in.env
is not a valid purchased number associated with your MessageBird account, or it's an alphanumeric sender ID that is not permitted for the recipient's country or mobile carrier. Alphanumeric IDs also cannot be used in some countries (like the US)..env
. Ensure purchased numbers are entered in the correct international E.164 format (+
followed by country code and number, e.g.,+447123456789
). Check MessageBird's documentation on country restrictions for alphanumeric sender IDs or switch to using a purchased virtual number.invalid recipient
/recipient not found
recipient
phone number provided in the API request body is not in a valid international format (e.g., missing the+
prefix or country code), contains invalid characters, or represents a number that does not exist or is unreachable.+14155552671
). Verify the number itself is correct.Cannot POST /webhook/inbound-sms
(404):index.js
beforeapp.listen()
. Ensure the URL in Flow Builder exactly matches your route path.recipient
field (your MessageBird number) cannot be used as originator for replies; insufficient account balance; API key issues.Frequently Asked Questions About MessageBird Two-Way SMS
How do I receive SMS messages with MessageBird Node.js SDK?
To receive SMS with MessageBird, purchase a virtual number with SMS capability, create a webhook endpoint in your Express app (
POST /webhook/inbound-sms
), configure Flow Builder in the MessageBird dashboard to forward incoming SMS to your webhook URL, and process the form-encoded payload containing the sender's number and message content. Learn more about webhook configuration and implementing inbound SMS handlers.Can I use MessageBird for two-way SMS conversations?
Yes, MessageBird supports two-way SMS messaging. Purchase a virtual phone number (not an alphanumeric sender ID), set up webhook endpoints to receive inbound SMS, and use the MessageBird API to send replies. Alphanumeric sender IDs only support one-way outbound messaging. See the complete two-way SMS implementation guide.
What's the difference between MessageBird and Bird API?
MessageBird rebranded as "Bird" in February 2024 with 90% price reductions. The legacy MessageBird API (developers.messagebird.com) continues to be supported but no longer accepts new customers. New integrations should use the Bird API (docs.bird.com). Both support two-way SMS messaging with similar SDK patterns.
How do I test MessageBird webhooks locally?
Use a tunneling service like ngrok to expose your local Express server to the internet. Run
ngrok http 3000
to get a public HTTPS URL, then configure that URL in MessageBird Flow Builder. Send SMS to your MessageBird number to test the webhook locally. For detailed setup instructions, see the webhook testing section.What are the SMS rate limits for MessageBird in the US?
US and Canadian MessageBird numbers have rate limits of 500 SMS per day per number and 1 SMS per second throughput. To send more messages, purchase additional virtual numbers (e.g., 3 numbers = 3 SMS/second and 1,500 SMS/day). Learn more about MessageBird rate limits.
How much does a MessageBird SMS cost?
MessageBird SMS pricing varies by destination country. After the February 2024 rebrand to "Bird," prices were reduced by 40-90%. Check the MessageBird Pricing API or dashboard for specific rates. Messages are billed per segment: 160 characters (GSM-7) or 70 characters (UCS-2 with emojis). Understand SMS character limits and pricing.
10. Deploy Your SMS Application to Production
Deploying this application involves running the Node.js server in a production environment (like a cloud virtual machine or a Platform-as-a-Service) and ensuring the environment variables are configured securely.
.env
file to Git or upload it directly. Use the deployment platform's specific mechanism for setting environment variables (e.g., Heroku config vars, AWS Parameter Store/Secrets Manager, Vercel Environment Variables). SetMESSAGEBIRD_API_KEY
andMESSAGEBIRD_ORIGINATOR
in the production environment. You might also want to setNODE_ENV=production
.node index.js
. Alternatively, define astart
script in yourpackage.json
("start": "node index.js"
) and configure the platform to runnpm start
.process.env.PORT || 3000
. Most PaaS platforms automatically set thePORT
environment variable, which your application will correctly bind to.Example (Conceptual Heroku Deployment):
heroku login
).git init
,git add .
,git commit -m "Initial commit"
).heroku create your-unique-sms-app-name
git push heroku main
(ormaster
, depending on your branch name).heroku logs --tail
.11. Enhance Your Two-Way SMS Application
You have successfully built a service with bidirectional SMS capabilities using Node.js, Express, and MessageBird. From here, you can expand its capabilities:
Enhance Two-Way Messaging:
Explore More MessageBird/Bird Features:
Remember to replace placeholders like
YOUR_LIVE_API_KEY_HERE
,YOUR_PURCHASED_NUMBER_OR_SENDER_ID
, andYOUR_RECIPIENT_PHONE_NUMBER
with your actual values during setup and testing.