Frequently Asked Questions
You can send SMS messages by creating a Fastify API endpoint that uses the MessageBird API. This involves setting up a Node.js project with Fastify, the MessageBird SDK, and dotenv, then configuring a POST route to handle SMS sending requests. The route handler extracts recipient and message details, interacts with the MessageBird API, and returns a response indicating success or failure.
MessageBird is a Communication Platform as a Service (CPaaS) that provides APIs for various communication channels, including SMS. In a Node.js application, the MessageBird Node.js SDK allows you to programmatically send SMS messages, manage phone numbers, and access other communication features offered by MessageBird.
Fastify is a high-performance web framework known for its speed and ease of use. Its built-in features like validation and logging simplify the development process, while its efficiency ensures your SMS sending API can handle a reasonable volume of requests.
Alphanumeric sender IDs (e.g., 'MyApp') can be used as an alternative to phone numbers when sending SMS messages through MessageBird. However, their support and restrictions vary by country. Check MessageBird's documentation to ensure compatibility and consider that numeric sender IDs (phone numbers) are generally more reliable.
Yes, it's highly recommended to use environment variables (like those managed by a .env file) to store sensitive information like your MessageBird API key. This keeps your credentials out of your source code, improving security, especially important for projects shared or deployed publicly.
Use a try...catch block to handle potential errors during the MessageBird API call within your route handler. The MessageBird SDK returns structured error objects that can help identify the issue. Fastify also provides robust error handling capabilities.
Standard SMS messages are limited to 160 GSM-7 characters. Longer messages will be split into multiple parts. If using Unicode characters (like emojis), the character limit per part is significantly reduced (often down to 70).
You can set up rate limiting to control how many requests your Fastify API endpoint will accept within a given time period. This helps mitigate abuse and ensure service availability. The recommended way to do this is using the '@fastify/rate-limit' plugin.
You can test your SMS API endpoint using tools like curl or Postman to send POST requests. These tools allow you to specify the recipient phone number, message content, and necessary headers. Observe the responses to verify successful delivery or debug any issues.
Deploying a Fastify application typically involves selecting a hosting provider (e.g. Heroku, AWS, Google Cloud) and configuring it to run your Node.js server. Ensure environment variables (like your MessageBird API key) are set securely in the hosting environment, not in committed files.
You'll need Node.js, npm (or yarn), a MessageBird account with a purchased phone number or verified sender ID, and a text editor. A basic understanding of Node.js, JavaScript, and REST APIs is helpful.
Use npm (or yarn) to install the required packages. Run 'npm install fastify messagebird dotenv' in your project's terminal to install Fastify, the MessageBird Node.js SDK, and the dotenv package for environment variable management.
Your MessageBird API key can be found in your MessageBird account dashboard. Go to 'Developers' -> 'API access'. Generate a Live API key if you don't have one, and copy it to use in your project's .env file.
Send SMS with Node.js, Fastify & MessageBird: Complete Tutorial (2025)
Build a production-ready Node.js SMS API using Fastify and MessageBird. This tutorial teaches you to send SMS messages programmatically with Node.js 22, Fastify v5, and the MessageBird SDK. You'll create a high-performance API endpoint that handles SMS delivery, implements proper error handling, and follows security best practices for production deployment.
By the end, you'll have a functional SMS API endpoint (
POST /send-sms
) that accepts phone numbers and message content, dispatches SMS through MessageBird, and handles edge cases with proper validation and logging. This forms a foundational building block for Node.js applications requiring SMS notifications, two-factor authentication, alerts, or customer communication features.Project Overview and Goals
POST /send-sms
) that sends SMS messages using the MessageBird Node.js SDK.dotenv
: Loads environment variables from a.env
file intoprocess.env
.node --version
to check your installed version.1. Setting up the Project
Initialize your Node.js project and install dependencies.
Create Project Directory: Open your terminal and create a new directory for the project, then navigate into it.
Initialize npm Project: Create a
package.json
file to manage dependencies and scripts.Install Dependencies: Install Fastify for the web server, the
messagebird
SDK for API interaction, anddotenv
for configuration management.Install Development Dependencies (Optional but Recommended): Install
nodemon
for automatic server restarts during development andpino-pretty
for readable logs.Configure
package.json
Scripts: Openpackage.json
and addstart
anddev
scripts to thescripts
section:npm start
: Runs the application using Node directly (for production).npm run dev
: Runs the application usingnodemon
with auto-reloading and pipes logs throughpino-pretty
for better readability.Create
.gitignore
: Prevent committing sensitive files and unnecessary folders. Create a.gitignore
file in the project root:Create Server File: Create the main application file.
Your project structure should now look like this:
2. Configuration: API Keys and Environment Variables
Never hardcode sensitive information like API keys directly into your source code. Use environment variables managed via a
.env
file.Create
.env
and.env.example
Files:.env
: Holds your actual secrets (not committed to version control)..env.example
: Template showing required variables (safe to commit).Define Environment Variables: Add these variables to both
.env.example
(with placeholder values) and.env
(with your actual values).How to Obtain Values:
MESSAGEBIRD_API_KEY
:.env
file.MESSAGEBIRD_ORIGINATOR
:+12005550199
) or an alphanumeric sender ID (e.g.,MyApp
, max 11 chars).+12005550199
). Purchased numbers (VMN) are more reliable and have fewer restrictions than alphanumeric IDs.+1214123456
or1214123456
(MessageBird accepts both with or without the + prefix)..env
file.PORT
:Load Environment Variables in
server.js
: At the very top ofserver.js
, require and configuredotenv
.3. Implementing the Core Functionality with Fastify
Build the Fastify server and the SMS sending endpoint.
Initialize Fastify and MessageBird SDK: In
server.js
, after loadingdotenv
, requirefastify
and initialize themessagebird
SDK using your API key from the environment variables.logger: true
enables Fastify's efficient Pino logger. During development (npm run dev
),pino-pretty
formats these logs nicely.Define the
/send-sms
Route: Create aPOST
route that accepts a JSON body containing therecipient
phone number and themessage
text. Fastify's schema validation ensures you receive the correct data format.sendSmsSchema
to validate the incomingrequest.body
. It requiresrecipient
(string matching E.164 pattern) andmessage
(non-empty string). Fastify automatically returns400 Bad Request
if validation fails.async
to useawait
.messagebird.messages.create
uses a traditional Node.js callback pattern, wrap it in aPromise
to useasync/await
for cleaner asynchronous flow.params
object required by the MessageBird SDK, ensuringrecipients
is an array.try...catch
block handles potential errors during the API call. Log errors and send an appropriate HTTP status code (500 for general errors, or 400/specific codes if MessageBird provides them) and message back to the client.Start the Fastify Server: Add the code to start listening for connections at the end of
server.js
.async
functionstart
.fastify.listen
starts the server. Parse thePORT
from environment variables (defaulting to 3000) and listen on0.0.0.0
to accept connections from outside localhost (important for deployment).4. Error Handling and Logging
400 Bad Request
with details about the validation failure.catch
block in the route handler looks for the structure of MessageBird errors (error.errors
) to provide specific feedback and potentially use status codes returned by MessageBird (like400
for bad input).500 Internal Server Error
.request.log.info
,request.log.error
) provides contextual logging for each request. In development (npm run dev
), logs are prettified. In production, the default JSON format suits log aggregation systems.5. Security Considerations
Consider these security measures for production:
API Key Security: Never commit your
.env
file or expose yourMESSAGEBIRD_API_KEY
. Use environment variables in your deployment environment.Input Validation: Basic validation is implemented with Fastify schemas. For more complex scenarios, consider libraries like
joi
or more specific validation logic. Sanitize any input that might be stored or displayed elsewhere.Rate Limiting: Implement rate limiting on the
/send-sms
endpoint to prevent abuse. The@fastify/rate-limit
plugin is excellent for this.await fastify.register(...)
call must be inside anasync
function context, like thestart
function, before routes are defined. Check the@fastify/rate-limit
documentation for the correct import/require syntax for your setup.Authentication/Authorization: If this API is part of a larger system, protect the endpoint. Ensure only authorized clients or users can trigger SMS sending (e.g., using JWT, API keys for clients, session authentication).
6. Testing the Endpoint
Test the endpoint using tools like
curl
or Postman.Start the Development Server:
You should see output indicating the server is running, similar to:
{"level":30,"time":...,"pid":...,"hostname":"...","msg":"Server listening on port 3000"}
Send a Test Request using
curl
: Open another terminal window. Replace placeholders with your actual test recipient number (in E.164 format) and a message.Check the Response:
Success: You should receive a
200 OK
response similar to this (details will vary):You should receive the SMS on the recipient phone shortly after.
Validation Error (e.g., missing field):
Response (
400 Bad Request
):MessageBird API Key Error (e.g., invalid key in
.env
): Response (401 Unauthorized
or similar, depending on MessageBird):Check Server Logs: Observe the logs in the terminal where
npm run dev
is running for detailed information about requests and errors.7. Troubleshooting and Caveats
MESSAGEBIRD_API_KEY
in.env
. Ensure it's a Live key and correctly copied from the dashboard. Verifydotenv.config()
is called before initializing the MessageBird SDK.MESSAGEBIRD_ORIGINATOR
is either a valid E.164 number you own in MessageBird or a permitted alphanumeric ID for the destination country. Check MessageBird's country restrictions – numeric IDs generally have broader support.recipient
number in your test request uses correct E.164 format (+
followed by country code and number, e.g.,+447123456789
). MessageBird does not validate number format – incorrect formatting may result in delivery to wrong countries or failed delivery.rest.messagebird.com
. Firewalls could block outbound connections..env
Not Loaded: Verify the.env
file exists in the project root andrequire('dotenv').config();
is at the top ofserver.js
.^
,€
,~
,[
,]
,{
,}
,|
,\\
require two character spaces each, effectively reducing message length.8. Deployment and CI/CD
Deploy this application by running the Node.js process on a server and setting the correct environment variables.
npm start
(which executesnode server.js
).MESSAGEBIRD_API_KEY
,MESSAGEBIRD_ORIGINATOR
, andPORT
within your hosting platform's settings. Never commit your.env
file.NODE_ENV
: Set theNODE_ENV
environment variable toproduction
on your server. This enables optimizations in Fastify and dependencies.npm ci --only=production
is recommended for production installs).9. Verification
After deployment or changes, verify functionality using this checklist:
curl
or Postman against the deployed API URL to send a test message.Frequently Asked Questions (FAQ)
Q: How do I send SMS using Node.js and Fastify? A: Send SMS using Node.js and Fastify by installing the Fastify framework and MessageBird SDK, creating a POST endpoint with schema validation, and calling
messagebird.messages.create()
with the recipient number and message body. Configure your MessageBird API key via environment variables and use async/await for clean asynchronous code handling.Q: What is the best SMS API for Node.js applications? A: MessageBird is an excellent SMS API for Node.js applications due to its official Node.js SDK, competitive pricing, high delivery rates, and support for international messaging. Other popular options include Twilio, Sinch, and Plivo. MessageBird (now "Bird") provides reliable message delivery with detailed error reporting and status tracking.
Q: How many characters can I send in a single SMS message? A: A single SMS supports 160 characters using GSM-7 encoding (standard English text). Multi-part messages use 153 characters per segment (7 characters reserved for reassembly headers). Unicode messages (emoji, Arabic, Chinese) support 70 characters for single SMS or 67 characters per segment in multi-part messages.
Q: Do I need a MessageBird phone number to send SMS? A: You need either a purchased virtual mobile number (VMN) from MessageBird or an alphanumeric sender ID. Virtual mobile numbers are more reliable and have fewer country restrictions. Alphanumeric sender IDs (max 11 characters, like "MyApp") have limited support and may require pre-registration in regions like North America.
Q: How do I handle MessageBird API errors in Node.js? A: Handle MessageBird API errors by wrapping the SDK callback in a Promise, using try/catch blocks, and checking for the
error.errors
array structure. MessageBird returns structured error objects with status codes and descriptions. Log errors using Fastify's built-in Pino logger and return appropriate HTTP status codes (400 for validation errors, 401 for authentication, 500 for server errors).Q: What phone number format does MessageBird require? A: MessageBird requires E.164 format: country code followed by the subscriber number with no spaces, dashes, or parentheses. Example: US number (214) 123-4567 becomes
+1214123456
. MessageBird accepts numbers with or without the + prefix. However, MessageBird doesn't validate format—incorrect formatting may cause delivery to wrong countries.Q: How do I test SMS sending without using real phone numbers? A: Test SMS sending using MessageBird's Test API key for development (messages won't actually send). For real testing, use your own phone number as the recipient. MessageBird doesn't charge for failed deliveries, so testing with small volumes is cost-effective. Check the MessageBird dashboard's SMS Log under Insights to verify message status.
Q: Can I send SMS to multiple recipients at once with MessageBird? A: Yes, include multiple phone numbers in the
recipients
array parameter when callingmessagebird.messages.create()
. Example:recipients: ['+12005550199', '+447123456789']
. MessageBird charges per recipient, and each receives the same message. For personalized messages, send separate API requests for each recipient.Q: How do I implement rate limiting for my SMS API endpoint? A: Implement rate limiting using the
@fastify/rate-limit
plugin. Install withnpm install @fastify/rate-limit
, register the plugin before defining routes, and configure max requests per time window (e.g., 10 requests per minute per IP). This prevents API abuse and protects against spam while ensuring legitimate traffic flows smoothly.Q: What's the difference between MessageBird's Live and Test API keys? A: Test API keys simulate API behavior without sending actual SMS messages or charging your account. Live API keys send real SMS messages and deduct credits from your balance. Use Test keys during development and integration testing, then switch to Live keys for production deployment. Never commit API keys to version control—use environment variables.
Q: How do I deploy a Fastify SMS application to production? A: Deploy Fastify SMS applications by pushing code to platforms like Heroku, Render, AWS (EC2, Elastic Beanstalk, Lambda), or Google Cloud (Cloud Run). Set environment variables (
MESSAGEBIRD_API_KEY
,PORT
,NODE_ENV=production
) in your hosting platform's configuration. Usenpm start
as the start command and ensure your server listens on0.0.0.0
to accept external connections.Q: Why am I getting "Authentication failed" errors from MessageBird? A: "Authentication failed" errors occur when your API key is invalid, expired, or incorrectly configured. Verify you're using a Live API key (not Test) for production, check the key is correctly copied from the MessageBird dashboard without extra spaces, and confirm
dotenv.config()
is called before initializing the MessageBird SDK. Check the API access page in your MessageBird dashboard to regenerate keys if needed.Complete Code Repository
A complete, working example of this project may be available. Check project documentation or related resources for a link to the code repository if applicable.
Next Steps
This guide covers the basics of sending SMS. Extend this foundation by: