Frequently Asked Questions
Create a Next.js API route (/api/send-sms) that uses the MessageBird Node.js SDK to interact with the MessageBird API. This API route should handle POST requests containing the recipient's phone number and the message body. The frontend will call this route to trigger sending the SMS.
The MessageBird Node.js SDK simplifies the process of interacting with the MessageBird REST API for sending SMS messages from your Node.js or Next.js application. It handles the low-level details of API calls and error management.
Next.js API routes provide serverless functions that are ideal for backend logic like sending SMS. This avoids exposing your API key on the client-side and offers a secure way to manage the SMS sending process.
Alphanumeric Sender IDs (e.g., 'MyApp') can be used for branding, but they're not supported everywhere (like USA/Canada) and can't receive replies. Use a virtual mobile number for two-way communication.
Store your MessageBird API key and originator (sender ID/number) in a .env.local
file in your project's root directory. Next.js automatically loads these as environment variables. Never expose your API key to the frontend.
The originator is the sender ID or number that will appear on the recipient's phone. It can be an alphanumeric ID (max 11 chars), a virtual mobile number, or a verified phone number.
The MessageBird SDK provides error details in a callback function. Implement proper error handling in your API route to log errors and return informative error messages to the frontend. Check err.errors
for MessageBird-specific error codes.
Use the E.164 format for recipient phone numbers (e.g., +12025550182). This format includes the country code and ensures compatibility with MessageBird's global SMS delivery.
Implement server-side validation of phone numbers using a library like libphonenumber-js
. Also, implement rate limiting on your API endpoint to prevent abuse and consider using separate API keys for different environments.
Yes, log into the MessageBird dashboard and navigate to "SMS" > "Message Logs" to review sent messages, delivery statuses, and any potential errors encountered during the sending process.
Set up webhooks in your MessageBird account to receive inbound messages. Your webhook URL should point to a Next.js API route configured to handle these incoming message events.
Enhance your application by adding input validation, user authentication, message history tracking, or implementing inbound message handling using MessageBird webhooks.
Send SMS with MessageBird and Next.js: Complete Integration Guide
Learn how to send SMS messages programmatically using MessageBird (Bird) and Next.js. This step-by-step guide shows you how to integrate the MessageBird SMS API with Next.js API routes to build a complete SMS messaging solution. You'll create a web form that captures recipient phone numbers and messages, then securely sends SMS via MessageBird's Node.js SDK.
Discover how to implement SMS notifications, alerts, and transactional messages in your Next.js app, leveraging serverless functions for secure backend logic. This tutorial covers setup, authentication, error handling, and production deployment best practices. Learn to send SMS messages with proper security, rate limiting, and phone number validation.
Important Note (2025): MessageBird rebranded as "Bird" in February 2024. The MessageBird APIs, SDKs, and developer documentation remain fully functional and compatible. This guide uses the established MessageBird Node.js SDK (v4.0.1, last updated January 2023), which continues to work with the current Bird platform. Source: TechCrunch, February 2024
Prerequisites:
originator
Project Overview and Goals
Goal: Create a Next.js application that lets users send SMS messages to specified phone numbers through a simple web interface, using MessageBird as the SMS provider.
Problem Solved: Add SMS capabilities to any Next.js project for sending notifications, confirmations, or transactional messages.
Technologies Used:
System Architecture:
How it works:
/api/send-sms
).Final Outcome: A functional Next.js application with a page containing a form. Submit the form to send an SMS message using the MessageBird API via a secure backend API route.
1. Setting up the Next.js Project
Create a new Next.js project and install the MessageBird SDK to enable SMS functionality.
Step 1: Create a Next.js App
Open your terminal and run the following command. Replace
messagebird-nextjs-sms
with your desired project name.Follow the prompts. Note: While
create-next-app
might default to the App Router, this guide uses the Pages Router structure (pages/api/send-sms.js
,pages/index.js
) for demonstrating the API route and frontend form.Step 2: Navigate to Project Directory
Step 3: Install MessageBird Node.js SDK
Install the official MessageBird SDK for Node.js.
Step 4: Set up Environment Variables
Never hardcode API keys directly into your source code. Use environment variables instead. Next.js has built-in support for environment variables using
.env.local
files.Create a file named
.env.local
in the root of your project:Open
.env.local
and add your MessageBird API Key and originator phone number (or alphanumeric sender ID). Obtain these in the next section.MESSAGEBIRD_ACCESS_KEY
: Your live API access key from the MessageBird dashboardMESSAGEBIRD_ORIGINATOR
: The phone number (in E.164 format, e.g.,+12025550182
) or alphanumeric sender ID (max 11 characters, country restrictions apply) that the SMS will appear to be sent fromImportant: Add
.env.local
to your.gitignore
file (it should be there by default increate-next-app
) to prevent accidentally committing your secret keys.Project Structure (Simplified - Pages Router):
Why
.env.local
? Next.js automatically loads variables from this file intoprocess.env
on the server side (including API routes). Variables prefixed withNEXT_PUBLIC_
would be exposed to the browser – we do not want that for our API key.2. Getting MessageBird API Credentials
Before building the SMS API endpoint, you need your MessageBird API key and an originator (sender ID or phone number).
Step 1: Access the MessageBird Dashboard
Log in to your MessageBird Dashboard.
Step 2: Find/Create Your API Key
.env.local
file as the value forMESSAGEBIRD_ACCESS_KEY
.Step 3: Determine Your Originator
+12025550182
).MyApp
, max 11 characters). Go to Developers > Sender IDs to register one. Note: Alphanumeric IDs are not supported in all countries (e.g., USA, Canada) and cannot receive replies..env.local
file as the value forMESSAGEBIRD_ORIGINATOR
.Security Note: Treat your Live API Key like a password. Do not share it publicly or commit it to version control.
3. Building the SMS API Endpoint (
/api/send-sms
)Now, let's create the Next.js API route that handles SMS sending logic using the MessageBird SDK. API routes in Next.js (using the Pages Router) provide a seamless way to build backend functionality within your frontend project.
Step 1: Create the API Route File
Create a new file:
pages/api/send-sms.js
Step 2: Implement the API Logic
Paste the following code into
pages/api/send-sms.js
:Code Explanation:
initClient
function from themessagebird
package.initClient
with the API key loaded fromprocess.env.MESSAGEBIRD_ACCESS_KEY
. This must be done outside the handler function for efficiency./api/send-sms
.POST
requests are processed, returning a405 Method Not Allowed
otherwise. This is standard practice for API endpoints that perform actions.POST
requests intoreq.body
. We extractrecipient
andbody
.recipient
andbody
are present, returning a400 Bad Request
if not. More robust validation should be added in production (see Security section).params
object required by themessagebird.messages.create
method, ensuringrecipients
is an array.messagebird.messages.create
with the parameters and a callback function.err
object exists in the callback, an error occurred during the API call (network issue, invalid key, invalid parameters, etc.).console.error
.500 Internal Server Error
response to the frontend with a user-friendly message and potentially more details fromerr.errors
.err
is null, the API call was successful (though delivery isn't guaranteed instantly).200 OK
response to the frontend.4. Creating the SMS Frontend Interface
Let's build a React form component on the main page (
pages/index.js
) to collect the recipient phone number and message text, then call our SMS API endpoint.Step 1: Modify the Index Page
Replace the contents of
pages/index.js
with the following code:Code Explanation:
useState
to manage the input values (recipient
,messageBody
), loading state (isLoading
), error state (isError
), and feedback messages (statusMessage
).handleSubmit
Function:isLoading
to true and clears previous status messages.fetch
API to make aPOST
request to our/api/send-sms
endpoint.Content-Type
header toapplication/json
.recipient
andmessageBody
state values in the request body, stringified as JSON.response.json()
.response.ok
(status code 200-299) is true. If not, it throws an error using the message from the API response (result.message
) or a default HTTP error message.catch
): Catches network errors duringfetch
or errors thrown from the non-OK response handling. Logs the error and displays an error message to the user.finally
Block: SetsisLoading
back to false regardless of success or failure.onSubmit
handler pointing to ourhandleSubmit
function.input type="tel"
,textarea
) are controlled components, linked to the React state viavalue
andonChange
.isLoading
is true.statusMessage
below the form, styled differently based on theisError
state.styles/Home.module.css
or a global stylesheet.5. Running and Testing Your SMS Application
Now it's time to run the Next.js application and send your first SMS message using MessageBird!
Step 1: Start the Development Server
Open your terminal in the project root directory and run:
This will start the Next.js development server, usually on
http://localhost:3000
.Step 2: Open the Application
Open your web browser and navigate to
http://localhost:3000
. You should see the "Send SMS via MessageBird" page with the form.Step 3: Send a Test SMS
+12025550182
) that you can receive messages on. Use your own number for testing.Step 4: Verify
fetch
call.npm run dev
. You should see the log messages from the API route (Sending SMS via MessageBird...
andMessageBird API Success:...
orMessageBird API Error:...
).sent
,delivered
,failed
). This is crucial for debugging delivery issues.6. SMS Error Handling and Logging Best Practices
The basic SMS implementation includes error handling, but production applications require more robust error management.
API Route (
pages/api/send-sms.js
) Enhancements:err
object from the MessageBird callback often contains anerrors
array with specific codes and descriptions (e.g.,2
- invalid username/password,9
- invalid originator,10
- destination not reachable). Log these details.Frontend (
pages/index.js
) Enhancements:fetch
call, you could implement a simple retry mechanism, but be cautious not to bombard the API if the underlying issue persists.7. Security Best Practices for SMS APIs
Securing your SMS API endpoint and MessageBird credentials is critical for production applications.
API Key Security:
.env.local
or exposeMESSAGEBIRD_ACCESS_KEY
to the frontend JavaScript. Ensure.env.local
is in your.gitignore
.Input Validation (API Route):
!recipient || !body
) is minimal.libphonenumber-js
) on the server-side (API route) to validate that therecipient
is a plausible phone number format before sending it to MessageBird.body
length. While MessageBird handles concatenation, you might want to enforce limits or inform the user about multi-part messages for cost reasons.Phone Number Validation (Recommended Implementation):
libphonenumber-js
(v1.12.23 as of October 2025, actively maintained):Source: libphonenumber-js npm package, v1.12.23, last updated September 2025
Rate Limiting (API Route):
/api/send-sms
endpoint.rate-limiter-flexible
or Vercel's built-in IP rate limiting features. Limit requests per IP address over a specific time window (e.g., 5 requests per minute).Authentication/Authorization (If Applicable):
/api/send-sms
) verifies that the user making the request is authenticated and authorized to send SMS messages (e.g., using session cookies, JWTs, or NextAuth.js).8. Troubleshooting Common MessageBird SMS Issues
SDK Maintenance Note (2025): The MessageBird Node.js SDK (v4.0.1) was last updated in January 2023. While the SDK remains functional and compatible with the current Bird platform, it has not received recent updates. The SDK continues to work reliably for SMS functionality, but monitor the GitHub repository for any future updates or consider the REST API directly if you need the latest features. Source: GitHub messagebird-nodejs repository, 2025
Common issues you might encounter:
Invalid API Key:
2
- Authentication error).MESSAGEBIRD_ACCESS_KEY
in.env.local
. Ensure you are using the Live key (not Test, unless intended). Restart the dev server (npm run dev
) after changing.env.local
. Verify the key is correct in the MessageBird dashboard.Environment Variables Not Loaded:
process.env
..env.local
(not.env
or.env.development
). Ensure variable names match (MESSAGEBIRD_ACCESS_KEY
,MESSAGEBIRD_ORIGINATOR
). Restart the dev server after creating/modifying the file.Invalid Recipient Number:
10
- destination not reachable, or validation errors). Frontend might show success initially if the API call itself succeeded but delivery failed later.+1...
,+44...
). Check the MessageBird Message Logs for specific delivery failure reasons. Implement server-side phone number validation.Invalid Originator:
9
- invalid originator).MESSAGEBIRD_ORIGINATOR
in.env.local
. Ensure the number is owned/verified in your MessageBird account, or the Alphanumeric Sender ID is registered and allowed in the destination country.Alphanumeric Sender ID Restrictions:
MessageBird API Downtime/Errors:
Development Server Restart: Remember to restart your Next.js development server (
npm run dev
) after making changes to.env.local
or installing new dependencies.9. Deploying Your Next.js SMS Application
Deploying your Next.js application with MessageBird SMS integration to production is straightforward with modern platforms.
Using Vercel (Recommended for Next.js):
.env.local
andnode_modules/
) is pushed to a Git provider (GitHub, GitLab, Bitbucket).MESSAGEBIRD_ACCESS_KEY
: Your Live API key.MESSAGEBIRD_ORIGINATOR
: Your chosen sender ID/number.Other Platforms (Netlify, AWS Amplify, Docker, Node Server):
npm run build
) and deploy the output (.next
directory,public
,package.json
, etc.).MESSAGEBIRD_ACCESS_KEY
andMESSAGEBIRD_ORIGINATOR
. Never bundle.env.local
in your deployment artifact.10. SMS Integration Testing Checklist
After deployment (or during development), verify your MessageBird SMS integration with these checks:
sent
ordelivered
status? Check forfailed
status and reasons..env.local
is not in your Git repository.Next Steps: Advanced SMS Features
This guide covers the basics of sending SMS with MessageBird and Next.js. You can extend this implementation by:
libphonenumber-js
for phone numbers.Related Resources
For more advanced SMS implementations with Next.js and MessageBird, explore these guides:
This guide provides a solid foundation for integrating MessageBird SMS capabilities into your Next.js projects securely and effectively. Remember to prioritize security, especially around API key management and input validation. Happy coding!