Frequently Asked Questions
Create a Next.js API route that interacts with the MessageBird Batch API. This route should handle recipient input, construct the API payload, make the request to MessageBird, and process the response. A frontend form can collect recipient numbers and the message body, then trigger this API route.
The MessageBird SMS Batch API is a service that allows you to send a single SMS message to multiple recipients in one API call. It's more efficient than sending individual messages and simplifies message management.
Next.js API routes offer a serverless function environment ideal for handling backend logic like interacting with external APIs such as MessageBird. They are easy to set up and manage, making integration straightforward.
Bulk SMS is beneficial when you need to send the same message to many recipients simultaneously, like for alerts, notifications, or marketing communications. This guide's implementation is specifically for sending one message to up to 50 recipients at once.
This guide's code handles a maximum of 50 recipients per API call. To send to more, you'll need to modify the API route to split the recipient list into chunks of 50 and make separate API calls for each chunk. This chunking logic is not included in the basic guide.
Store your API key in a .env.local file. Next.js loads these variables into process.env server-side. This file is included in .gitignore to prevent accidental commits of sensitive data. Never expose your API key in frontend code.
The MESSAGEBIRD_ORIGINATOR sets the sender ID that recipients see. It can be a phone number (E.164 format) or an alphanumeric string (up to 11 characters). Consult MessageBird documentation and country-specific regulations before using alphanumeric sender IDs, as restrictions often apply.
The provided code includes basic error handling and logging. For production, use a logging library like Pino or Winston for better tracking. MessageBird API responses should also be thoroughly checked for errors, and proper error responses returned to the client.
Phone numbers should use the international E.164 format (e.g., +14155552671). This format includes the '+' sign and country code, ensuring consistent and reliable message delivery. For production, use a dedicated library like libphonenumber-js to enforce and validate the format.
To get final delivery reports, you need to set a reportUrl in your MessageBird API request. This URL should point to an endpoint in your application that can handle MessageBird webhooks (DLR callbacks) and then update internal statuses.
For sending to large recipient lists (hundreds or thousands), the Batch API isn't the best approach due to the recipient limit per message. In production, consider using queues or a dedicated MessageBird product designed for large-scale messaging, and implement chunking in your API route to respect the recipient limit per API call (50 in this implementation).
Common issues include invalid API keys, incorrect sender IDs (MESSAGEBIRD_ORIGINATOR), and invalid recipient phone numbers. Always double-check these and consult MessageBird documentation for specific error codes.
The official MessageBird API documentation is the best resource for details on API usage, limits, webhooks, error codes, and other features. Refer to it throughout the integration process for the most up-to-date information.
MessageBird Bulk SMS with Next.js: Complete Implementation Guide
Sending SMS messages to multiple recipients simultaneously – bulk or broadcast messaging – is a common requirement for applications distributing alerts, notifications, or marketing communications efficiently. Integrate directly with an SMS provider's API to control sending logic, manage costs, and handle responses effectively.
This guide walks you through building a production-ready bulk SMS feature in Next.js using the MessageBird SMS Batch API. You'll learn to set up the project, create a secure API endpoint to interact with MessageBird, implement error handling, and build a simple frontend interface for sending messages. The implementation includes TypeScript, Next.js App Router, and handles up to 50 recipients per request.
Important Note (January 2025): MessageBird rebranded as Bird in February 2024. While the legacy MessageBird API endpoints (developers.messagebird.com) remain operational and are used in this guide, the company now operates under bird.com with new API endpoints at api.bird.com. Third-party integrations may require updates. This guide uses the stable legacy MessageBird API endpoints, which remain functional as of January 2025.
By the end of this guide, you'll build a functional Next.js application that accepts a list of recipients and a message body, securely sends these messages via MessageBird's Batch API, and handles success/error feedback.
What you'll build: MessageBird bulk SMS system
What you'll build:
/api/send-bulk-sms).Common use cases for bulk SMS:
This implementation is perfect for sending appointment reminders, emergency alerts, promotional campaigns, delivery notifications, or any scenario where you need to reach multiple users simultaneously with the same message.
Problem solved:
This implementation addresses the need to programmatically send SMS messages to many users at once without manual intervention or iterating individual API calls, which is inefficient and harder to manage. It provides a scalable way to integrate bulk SMS capabilities directly into a web application.
Technologies used:
System architecture:
Prerequisites:
node --version.Setting up your Next.js bulk SMS project
Create a new Next.js project and set up the necessary environment configuration.
Important for Next.js 15 users: Next.js 15 (released October 2024) introduced breaking changes including async Request APIs and changed caching defaults for GET Route Handlers. This guide's code is compatible, but if you're using Next.js 15+,
cookies(),headers(), and similar functions now return Promises. The code in this guide uses standardfetchand doesn't use these APIs, so it remains compatible.1.1 Create a Next.js application
Open your terminal and run the following command to create a new Next.js project using the App Router. Replace
messagebird-bulk-smswith your desired project name.Follow the prompts. Recommended settings:
src/directory? Yes1.2 Navigate to the project directory
1.3 Configure environment variables
Store your MessageBird API key and sender ID (originator) securely. Create a file named
.env.localin the root of your project..env.local? Next.js automatically loads variables from this file intoprocess.envon the server side. It's included in.gitignoreby default, preventing accidental commits of sensitive keys.Add the following lines to
.env.local:YOUR_MESSAGEBIRD_ACCESS_KEYwith your actual key from the MessageBird dashboard (Developers > API access).YourSenderIDwith your desired originator (phone number or alphanumeric string).Security best practice: Never commit
.env.localto version control. Rotate API keys regularly and use test keys during development, switching to live keys only in production.1.4 Project structure
Your key files will be:
src/app/page.tsx: The simple frontend UI.src/app/api/send-bulk-sms/route.ts: The backend API route handling MessageBird interaction..env.local: Stores sensitive credentials.No additional dependencies are required for this basic implementation – use the built-in
fetchAPI.Building the MessageBird Batch API integration
Create the core backend logic – the API route that communicates with MessageBird.
2.1 Create the API route file
Create the following directory structure and file within the
srcdirectory:2.2 Implement the API route logic
Paste the following code into
src/app/api/send-bulk-sms/route.ts:Code explanation:
MESSAGEBIRD_ACCESS_KEYandMESSAGEBIRD_ORIGINATORare loaded from.env.local. Returns a 500 error if missing.recipientsis a non-empty array andbodyis a non-empty string.libphonenumber-jsto ensure recipients are in the correct E.164 format.fetchto make thePOSTrequest with correct headers.response.ok. Parses success or error responses from MessageBird. Returns202 Acceptedon success.try...catchhandles various errors. Logs detailed errors server-side and returns appropriate client-facing error messages and status codes.console.logandconsole.errorfor debugging. In production, replace these with a proper logging library (e.g., Pino, Winston).Testing the API endpoint (optional but recommended):
Test this endpoint using
curlor a tool like Postman before building the frontend.npm run devcurlcommand (replace placeholders with your test numbers and ensure the server runs on port 3000):You should see a JSON response indicating success (status 202) or an error (status 400 or 500). Check the terminal running the Next.js server for detailed logs, and your MessageBird dashboard (Logs > SMS) to verify message processing.
Creating the frontend SMS form
Create a simple page to interact with your API route.
3.1 Update the home page
Replace the content of
src/app/page.tsxwith the following code:Code explanation:
'use client': Marks this as a Client Component for using hooks and event handlers.recipientsInput,messageBody), loading state (loading), and API response feedback (responseInfo).handleSubmitFunction:POSTrequest to/api/send-bulk-sms.try...catchfor fetch errors.finallyblock.Testing your bulk SMS application
Run the application and test the end-to-end flow.
4.1 Run the development server
If not already running, start the server from your project root:
4.2 Test in the browser
http://localhost:3000.4.3 Test error scenarios:
MESSAGEBIRD_ACCESS_KEYin.env.local, restart the server, and submit. Expect an error message indicating a communication failure with the provider. Restore the key afterward.Security best practices for bulk SMS
.env.localor expose yourMESSAGEBIRD_ACCESS_KEYin frontend code. Use it only server-side.libphonenumber-jswithin the API route (/api/send-bulk-sms/route.ts)./api/send-bulk-sms) from abuse. Implement rate limiting to prevent rapid, excessive SMS sending. Tools likeupstash/ratelimitintegrated with Next.js middleware are common solutions.Error handling and logging
console.log/console.error. For production, replace these with a robust logging library (e.g., Pino, Winston). This enables structured logging, setting levels, and sending logs to external services (Datadog, Sentry, etc.) for better monitoring and debugging.reportUrlin the MessageBird API payload (see commented line inroute.ts). This URL should point to another API route in your Next.js app (e.g.,/api/message-status)./api/message-statusroute to securely receivePOSTrequests from MessageBird containing delivery reports (DLRs).delivered,delivery_failed, etc.Troubleshooting common MessageBird issues
.env.localfor correctness. Restart the dev server after changes. Look for 401 errors from MessageBird in server logs.MESSAGEBIRD_ORIGINATORis valid for your account and complies with regulations in recipient countries. Check MessageBird docs and country rules first.+14155552671). Incorrect formats cause failures. Use validation libraries.Deploying your Next.js bulk SMS app
MESSAGEBIRD_ACCESS_KEYandMESSAGEBIRD_ORIGINATORin your hosting provider's environment variable settings. Do not rely on.env.localin production.Frequently Asked Questions (FAQ)
How do I send bulk SMS with MessageBird in Next.js?
Use MessageBird's Batch API endpoint (
/messages/batches) with a Next.js API route. Create a POST endpoint that constructs a payload with amessagesarray containing recipient lists and message content, then send it using the Fetch API with your MessageBird Access Key for authentication.What is the MessageBird Batch API recipient limit?
The MessageBird Batch API allows a maximum of 100 message objects per request, with each message object supporting up to 50 recipients. This guide's implementation sends one message object per API call, limiting it to 50 recipients per request.
How do I handle more than 50 recipients with MessageBird?
To send to more than 50 recipients, implement chunking logic to split your recipient list into groups of 50, then make multiple API calls to MessageBird's Batch API. Each chunk becomes a separate API request with its own message object.
Is MessageBird compatible with Next.js 15?
Yes, MessageBird's API is compatible with Next.js 15. However, Next.js 15 (released October 2024) requires Node.js v18.18.0 or later and introduced async Request APIs. This guide's code uses the standard Fetch API and remains fully compatible with both Next.js 14 and 15.
What happened to MessageBird – did it rebrand?
MessageBird rebranded as Bird in February 2024. The legacy API endpoints at rest.messagebird.com remain operational as of January 2025, but the company now operates under bird.com with new API endpoints at api.bird.com. Consider migrating to Bird's new API structure for long-term projects.
How do I validate phone numbers for MessageBird SMS?
Use the E.164 international phone number format (e.g., +12025550181). For production applications, implement robust validation using a library like
libphonenumber-jsrather than basic regex patterns, as phone number validation has many edge cases across different countries.How do I track MessageBird SMS delivery status?
Implement webhooks by adding a
reportUrlparameter to your MessageBird API payload. This URL points to another API route in your Next.js application that receives delivery reports (DLRs) from MessageBird with statuses likedeliveredordelivery_failed.What Node.js version do I need for Next.js bulk SMS?
You need Node.js v18.18.0 or later for Next.js 15 (released October 2024). Verify your version with
node --version. Earlier Next.js versions support older Node.js versions, but v18.18.0+ is recommended for the latest features and security updates.How much does MessageBird bulk SMS cost?
MessageBird pricing varies by destination country and message volume. Typical costs range from $0.01-$0.10 per SMS segment depending on the destination. Contact MessageBird sales for enterprise pricing and volume discounts. Monitor your MessageBird dashboard for real-time balance and usage tracking.
Can I send international SMS with MessageBird Batch API?
Yes, MessageBird supports international SMS delivery to 200+ countries. Ensure recipient numbers use E.164 format with the correct country code (e.g., +44 for UK, +91 for India). Note that pricing, delivery rates, and sender ID regulations vary by country. Check MessageBird's country-specific SMS guides before sending international messages.
Conclusion
You've successfully implemented a bulk SMS sending feature in a Next.js application using the MessageBird Batch API, limited to 50 recipients per submission in this implementation. You created a secure API route and a simple frontend interface. Key takeaways include secure API key handling, constructing the Batch API payload, error handling, understanding the 50-recipient limit per call for this setup, and the need for webhooks for final delivery status.
Important reminder: MessageBird rebranded as Bird in February 2024. While the legacy API endpoints used in this guide remain functional (verified January 2025), monitor for future deprecation announcements and consider migrating to Bird's new API structure at api.bird.com for long-term projects.
Next steps and potential enhancements:
reportUrland a dedicated endpoint.libphonenumber-jsfor E.164 validation.This foundation enables you to send bulk SMS messages from your Next.js application. Consult the official MessageBird API documentation (developers.messagebird.com) or Bird documentation (docs.bird.com) for the latest features and details, especially regarding API limits, webhooks, and originator regulations.