code examples

Sent logo
Sent TeamMay 3, 2025 / code examples / Article

How to Send SMS with MessageBird and Next.js: Complete API Integration Guide (2025)

Learn how to send SMS messages using MessageBird (Bird) API with Next.js. Step-by-step tutorial covering API routes, authentication, error handling, and deployment best practices.

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:

  • Node.js LTS version (v18+ for Next.js 15) with npm or yarn installed
  • MessageBird account with valid API key (create accounts at messagebird.com or bird.com – both access the same platform)
  • Registered phone number (purchased from MessageBird or verified) to use as the originator
  • Basic understanding of React and Next.js concepts
  • Next.js Compatibility: This guide uses the Pages Router structure. While Next.js 15 recommends the App Router with Route Handlers for new projects, Pages Router API routes remain fully supported. Source: Next.js Documentation, 2025

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:

  • Next.js: React framework providing server-side rendering, static site generation, and API routes for full-stack web applications
  • Node.js: Runtime environment for Next.js and the MessageBird SDK
  • MessageBird Node.js SDK: Official SDK that simplifies interaction with the MessageBird REST API for sending SMS messages
  • MessageBird SMS API: Cloud messaging service for dispatching SMS messages globally with high deliverability

System Architecture:

text
+-----------------+      +---------------------+      +--------------------+      +-------------------+
| User (Browser)  | ---> | Next.js Frontend  | ---> | Next.js API Route | ---> | MessageBird API |
| (Input Form)    |      | (React Component)   |      | (/api/send-sms)   |      | (Sends SMS)       |
+-----------------+      +---------------------+      +--------------------+      +-------------------+
       |                                                       ^
       | (Success/Error)                                       | (API Key)
       +-------------------------------------------------------+

How it works:

  1. Enter a recipient number and message into the Next.js frontend form.
  2. On submission, the frontend makes an HTTP POST request to the Next.js API route (/api/send-sms).
  3. The API route initializes the MessageBird SDK using your stored API key.
  4. The API route calls the MessageBird API to send the SMS.
  5. MessageBird API sends the SMS to the recipient.
  6. The API route returns a success or error response to the frontend.
  7. The frontend displays feedback to you.

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.

bash
npx create-next-app@latest messagebird-nextjs-sms

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

bash
cd messagebird-nextjs-sms

Step 3: Install MessageBird Node.js SDK

Install the official MessageBird SDK for Node.js.

bash
npm install messagebird
# or using yarn
# yarn add messagebird

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:

bash
touch .env.local

Open .env.local and add your MessageBird API Key and originator phone number (or alphanumeric sender ID). Obtain these in the next section.

text
# .env.local

MESSAGEBIRD_ACCESS_KEY=YOUR_MESSAGEBIRD_LIVE_API_KEY
MESSAGEBIRD_ORIGINATOR=YOUR_SENDER_ID_OR_NUMBER
  • MESSAGEBIRD_ACCESS_KEY: Your live API access key from the MessageBird dashboard
  • MESSAGEBIRD_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 from

Important: Add .env.local to your .gitignore file (it should be there by default in create-next-app) to prevent accidentally committing your secret keys.

Project Structure (Simplified - Pages Router):

text
messagebird-nextjs-sms/
├── .env.local           # Your secret API key and originator
├── .gitignore
├── node_modules/
├── pages/
│   ├── api/
│   │   └── send-sms.js  # Our API endpoint logic
│   └── index.js         # Our frontend page with the form
├── public/
├── styles/              # Contains CSS modules or global styles
├── package.json
└── ... other config files

Why .env.local? Next.js automatically loads variables from this file into process.env on the server side (including API routes). Variables prefixed with NEXT_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

  • Navigate to the "Developers" section in the left-hand sidebar.
  • Click on the "API access" tab.
  • You will see options for "Live API Key" and "Test API Key". For sending actual messages, you need the Live API Key.
  • Copy the Live API Key. If you don't have one, you might need to create it.
  • Paste this key into your .env.local file as the value for MESSAGEBIRD_ACCESS_KEY.

Step 3: Determine Your Originator

  • This is the "from" address for your SMS. It can be:
    • A Virtual Mobile Number: Purchase one from MessageBird under the "Numbers" section. These are recommended for two-way communication and better deliverability in many regions. Use the full number in E.164 format (e.g., +12025550182).
    • An Alphanumeric Sender ID: A custom name (e.g., 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.
    • A Verified Number: You might be able to use your own verified mobile number in some cases, but purchasing a dedicated number is generally preferred for applications.
  • Paste your chosen originator into your .env.local file as the value for MESSAGEBIRD_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:

javascript
// pages/api/send-sms.js

// Import the MessageBird SDK initializer
import { initClient } from 'messagebird';

// Initialize the MessageBird client with your API key
// Ensure MESSAGEBIRD_ACCESS_KEY is set in your .env.local file
const messagebird = initClient(process.env.MESSAGEBIRD_ACCESS_KEY);

export default function handler(req, res) {
  // Only allow POST requests
  if (req.method !== 'POST') {
    res.setHeader('Allow', ['POST']);
    return res.status(405).json({ message: `Method ${req.method} Not Allowed` });
  }

  // Extract recipient and message body from the request
  const { recipient, body } = req.body;

  // Basic validation
  if (!recipient || !body) {
    return res.status(400).json({ message: 'Recipient and message body are required.' });
  }

  // Get the originator from environment variables
  const originator = process.env.MESSAGEBIRD_ORIGINATOR;
  if (!originator) {
      console.error('Error: MESSAGEBIRD_ORIGINATOR environment variable not set.');
      return res.status(500).json({ message: 'Server configuration error: Originator not set.' });
  }

  // Prepare the message parameters
  const params = {
    originator: originator,
    recipients: [recipient], // Must be an array
    body: body,
  };

  console.log(`Sending SMS via MessageBird: To=${recipient}, From=${originator}, Body="${body}"`);

  // Use the MessageBird SDK to send the message
  messagebird.messages.create(params, function (err, response) {
    if (err) {
      // Handle MessageBird API errors
      console.error('MessageBird API Error:', err);
      // Provide more specific error details if available
      const errorDetails = err.errors ? err.errors.map(e => `${e.description} (Code: ${e.code})`).join(', ') : err.message;
      return res.status(500).json({
        message: `Failed to send SMS. ${errorDetails}`,
        error: err, // Optionally include raw error in development
      });
    }

    // Handle successful response
    console.log('MessageBird API Success:', response);
    // Check status from the response if needed, e.g., response.recipients.items[0].status
    return res.status(200).json({
      message: 'SMS sent successfully!',
      details: response, // Optionally include raw response
    });
  });
}

Code Explanation:

  1. Import SDK: We import the initClient function from the messagebird package.
  2. Initialize Client: We call initClient with the API key loaded from process.env.MESSAGEBIRD_ACCESS_KEY. This must be done outside the handler function for efficiency.
  3. Handler Function: The default export is the function Next.js runs for requests to /api/send-sms.
  4. Method Check: We ensure only POST requests are processed, returning a 405 Method Not Allowed otherwise. This is standard practice for API endpoints that perform actions.
  5. Body Parsing: Next.js automatically parses the JSON body of POST requests into req.body. We extract recipient and body.
  6. Basic Validation: We check if recipient and body are present, returning a 400 Bad Request if not. More robust validation should be added in production (see Security section).
  7. Originator Check: We fetch the originator from environment variables and return a 500 error if it's missing, indicating a server configuration issue.
  8. Prepare Parameters: We create the params object required by the messagebird.messages.create method, ensuring recipients is an array.
  9. Logging: We log the attempt to send the SMS for debugging purposes.
  10. Send Message: We call messagebird.messages.create with the parameters and a callback function.
  11. Error Handling (Callback):
    • If the err object exists in the callback, an error occurred during the API call (network issue, invalid key, invalid parameters, etc.).
    • We log the detailed error using console.error.
    • We return a 500 Internal Server Error response to the frontend with a user-friendly message and potentially more details from err.errors.
  12. Success Handling (Callback):
    • If err is null, the API call was successful (though delivery isn't guaranteed instantly).
    • We log the success response.
    • We return a 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:

javascript
// pages/index.js

import { useState } from 'react';
import Head from 'next/head';
import styles from '../styles/Home.module.css'; // Assuming default styles

export default function Home() {
  const [recipient, setRecipient] = useState('');
  const [messageBody, setMessageBody] = useState('');
  const [statusMessage, setStatusMessage] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [isError, setIsError] = useState(false);

  const handleSubmit = async (event) => {
    event.preventDefault(); // Prevent default form submission
    setIsLoading(true);
    setStatusMessage(''); // Clear previous status
    setIsError(false);

    try {
      const response = await fetch('/api/send-sms', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ recipient, body: messageBody }),
      });

      const result = await response.json();

      if (!response.ok) {
        // Handle errors from the API route (e.g., 4xx, 5xx)
        throw new Error(result.message || `HTTP error! status: ${response.status}`);
      }

      // Handle success
      setStatusMessage(result.message || 'SMS sent successfully!');
      setRecipient(''); // Clear form on success
      setMessageBody('');

    } catch (error) {
      // Handle fetch errors or errors thrown from API response
      console.error("Sending SMS failed:", error);
      setStatusMessage(`Error: ${error.message}`);
      setIsError(true);
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className={styles.container}>
      <Head>
        <title>Send SMS with Next.js & MessageBird</title>
        <meta name="description" content="Send SMS using Next.js and MessageBird" />
        <link rel="icon" href="/favicon.ico" />
      </Head>

      <main className={styles.main}>
        <h1 className={styles.title}>
          Send SMS via MessageBird
        </h1>

        <form onSubmit={handleSubmit} className={styles.form}>
          <div className={styles.formGroup}>
            <label htmlFor="recipient">Recipient Phone Number:</label>
            <input
              type="tel"
              id="recipient"
              value={recipient}
              onChange={(e) => setRecipient(e.target.value)}
              placeholder="e.g., +12025550182" // E.164 format
              required
              disabled={isLoading}
            />
          </div>

          <div className={styles.formGroup}>
            <label htmlFor="messageBody">Message:</label>
            <textarea
              id="messageBody"
              value={messageBody}
              onChange={(e) => setMessageBody(e.target.value)}
              required
              rows={4}
              disabled={isLoading}
            />
          </div>

          <button type="submit" disabled={isLoading} className={styles.button}>
            {isLoading ? 'Sending...' : 'Send SMS'}
          </button>
        </form>

        {statusMessage && (
          <p className={`${styles.statusMessage} ${isError ? styles.error : styles.success}`}>
            {statusMessage}
          </p>
        )}
      </main>

      {/* Basic Styling (add to styles/Home.module.css or global.css for production) */}
      {/* Note: Inline JSX styles used here for demonstration purposes. */}
      <style jsx>{`
        .form {
          display: flex;
          flex-direction: column;
          gap: 1rem;
          width: 100%;
          max-width: 400px;
          margin-top: 2rem;
        }
        .formGroup {
          display: flex;
          flex-direction: column;
        }
        label {
          margin-bottom: 0.5rem;
          font-weight: bold;
        }
        input, textarea {
          padding: 0.75rem;
          border: 1px solid #ccc;
          border-radius: 4px;
          font-size: 1rem;
        }
        textarea {
          resize: vertical;
        }
        .button {
          padding: 0.75rem 1.5rem;
          background-color: #0070f3;
          color: white;
          border: none;
          border-radius: 4px;
          font-size: 1rem;
          cursor: pointer;
          transition: background-color 0.2s ease;
        }
        .button:disabled {
          background-color: #ccc;
          cursor: not-allowed;
        }
        .button:hover:not(:disabled) {
          background-color: #005bb5;
        }
        .statusMessage {
          margin-top: 1rem;
          padding: 0.75rem;
          border-radius: 4px;
          text-align: center;
        }
        .success {
          background-color: #d4edda;
          color: #155724;
          border: 1px solid #c3e6cb;
        }
        .error {
          background-color: #f8d7da;
          color: #721c24;
          border: 1px solid #f5c6cb;
        }
      `}</style>
    </div>
  );
}

Code Explanation:

  1. State Variables: We use useState to manage the input values (recipient, messageBody), loading state (isLoading), error state (isError), and feedback messages (statusMessage).
  2. handleSubmit Function:
    • Prevents the default form submission behavior (which would cause a page reload).
    • Sets isLoading to true and clears previous status messages.
    • Uses the fetch API to make a POST request to our /api/send-sms endpoint.
    • Sets the Content-Type header to application/json.
    • Sends the recipient and messageBody state values in the request body, stringified as JSON.
    • Response Handling:
      • Waits for the response and parses the JSON body using response.json().
      • Checks if 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.
      • If successful, it updates the status message and clears the form fields.
    • Error Handling (catch): Catches network errors during fetch or errors thrown from the non-OK response handling. Logs the error and displays an error message to the user.
    • finally Block: Sets isLoading back to false regardless of success or failure.
  3. JSX Form:
    • A standard HTML form element with an onSubmit handler pointing to our handleSubmit function.
    • Input fields (input type="tel", textarea) are controlled components, linked to the React state via value and onChange.
    • Placeholders guide the user (e.g., E.164 format for the phone number).
    • The submit button is disabled while isLoading is true.
    • Conditional rendering displays the statusMessage below the form, styled differently based on the isError state.
  4. Basic Styling: Inline JSX styles are included for demonstration. In a real application, move these to 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:

bash
npm run dev
# or using yarn
# yarn dev

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

  1. Recipient Phone Number: Enter a valid phone number (including country code, e.g., +12025550182) that you can receive messages on. Use your own number for testing.
  2. Message: Type a short test message.
  3. Click "Send SMS".

Step 4: Verify

  1. Frontend: Observe the status message below the form. It should indicate "SMS sent successfully!" or display an error.
  2. Your Phone: Check the recipient phone number for the incoming SMS message. It should arrive shortly.
  3. Developer Console (Browser): Check the browser's developer console (F12) for any potential frontend errors during the fetch call.
  4. Terminal Console (Server): Check the terminal where you ran npm run dev. You should see the log messages from the API route (Sending SMS via MessageBird... and MessageBird API Success:... or MessageBird API Error:...).
  5. MessageBird Dashboard: Log in to the MessageBird Dashboard and navigate to "SMS" > "Message Logs". You should see a record of the sent message, including its status (e.g., 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:

  • More Specific Logging: Log distinct messages for different error types (validation errors, MessageBird API errors, configuration errors).
  • Structured Logging: In production, consider using a dedicated logging library (like Pino or Winston) to output structured logs (JSON) which are easier to parse and analyze.
  • MessageBird Error Codes: The err object from the MessageBird callback often contains an errors array with specific codes and descriptions (e.g., 2 - invalid username/password, 9 - invalid originator, 10 - destination not reachable). Log these details.
javascript
// Example snippet within the callback in pages/api/send-sms.js
  messagebird.messages.create(params, function (err, response) {
    if (err) {
      console.error({
        message: 'MessageBird API Error occurred.',
        recipient: recipient,
        originator: originator,
        errorCode: err.errors ? err.errors[0]?.code : 'N/A',
        errorDescription: err.errors ? err.errors[0]?.description : err.message,
        details: err // Full error object for deeper debugging if needed
      });
      const userMessage = err.errors
         ? `Failed to send SMS: ${err.errors[0].description} (Code: ${err.errors[0].code})`
         : `Failed to send SMS. Please try again later.`;
      return res.status(500).json({ message: userMessage });
    }
    // ... success handling
  });

Frontend (pages/index.js) Enhancements:

  • User-Friendly Error Messages: Avoid showing raw technical error details directly to the user. Map common error statuses or messages from the API to simpler explanations.
  • Retry Logic (Optional): For transient network errors during the 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:

    • NEVER commit .env.local or expose MESSAGEBIRD_ACCESS_KEY to the frontend JavaScript. Ensure .env.local is in your .gitignore.
    • Use distinct API keys for different environments (development, staging, production).
    • Consider rotating API keys periodically.
  • Input Validation (API Route):

    • The current validation (!recipient || !body) is minimal.
    • Phone Number Validation: Use a library (like libphonenumber-js) on the server-side (API route) to validate that the recipient is a plausible phone number format before sending it to MessageBird.
    • Message Length: Check the body length. While MessageBird handles concatenation, you might want to enforce limits or inform the user about multi-part messages for cost reasons.
    • Sanitization: Although less critical for SMS content compared to HTML/SQL, ensure inputs don't contain unexpected characters that could break your system or MessageBird's processing if used elsewhere.
  • Phone Number Validation (Recommended Implementation):

    • Install libphonenumber-js (v1.12.23 as of October 2025, actively maintained):
    bash
    npm install libphonenumber-js
    • Add validation to your API route before sending SMS:
    javascript
    // pages/api/send-sms.js
    import { parsePhoneNumber, isValidPhoneNumber } from 'libphonenumber-js';
    
    export default function handler(req, res) {
      // ... existing method and body parsing code ...
    
      const { recipient, body } = req.body;
    
      // Validate phone number format
      if (!recipient || !isValidPhoneNumber(recipient)) {
        return res.status(400).json({
          message: 'Invalid phone number format. Please use E.164 format (e.g., +12025550182).'
        });
      }
    
      // Parse and format to E.164 if needed
      try {
        const phoneNumber = parsePhoneNumber(recipient);
        const formattedRecipient = phoneNumber.format('E.164');
        // Use formattedRecipient for MessageBird API call
      } catch (error) {
        return res.status(400).json({
          message: 'Unable to parse phone number. Please check the format.'
        });
      }
    
      // ... rest of your MessageBird code ...
    }

    Source: libphonenumber-js npm package, v1.12.23, last updated September 2025

  • Rate Limiting (API Route):

    • To prevent abuse (e.g., a bot spamming SMS via your form), implement rate limiting on the /api/send-sms endpoint.
    • Use libraries like 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):

    • If this feature is part of a larger application requiring users to log in, ensure the API route (/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:

    • Symptom: API route returns 500 error. Terminal logs show MessageBird error (often code 2 - Authentication error).
    • Solution: Double-check 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:

    • Symptom: API route returns 500 error. Terminal logs show "Server configuration error: Originator not set" or similar related to process.env.
    • Solution: Ensure the file is named exactly .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:

    • Symptom: API returns 500 error. Terminal logs show MessageBird error (e.g., code 10 - destination not reachable, or validation errors). Frontend might show success initially if the API call itself succeeded but delivery failed later.
    • Solution: Ensure the recipient number is in full E.164 format (e.g., +1..., +44...). Check the MessageBird Message Logs for specific delivery failure reasons. Implement server-side phone number validation.
  • Invalid Originator:

    • Symptom: API returns 500 error. Terminal logs show MessageBird error (e.g., code 9 - invalid originator).
    • Solution: Verify 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:

    • Symptom: Messages not delivered or originator is replaced, especially in countries like the US/Canada.
    • Solution: Use a purchased virtual mobile number as the originator for these countries. Check MessageBird's country restriction documentation.
  • MessageBird API Downtime/Errors:

    • Symptom: Intermittent 500 errors from your API route, potentially with specific MessageBird error codes related to temporary issues.
    • Solution: Implement robust logging to track these. Consider implementing retries with exponential backoff only for specific, transient error codes if necessary. Check MessageBird's status page.
  • 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):

  1. Push to Git: Ensure your code (excluding .env.local and node_modules/) is pushed to a Git provider (GitHub, GitLab, Bitbucket).
  2. Import Project: Log in to Vercel and import the Git repository. Vercel will typically auto-detect it as a Next.js project.
  3. Configure Environment Variables: This is crucial. In your Vercel project settings, navigate to "Settings" > "Environment Variables". Add the following:
    • MESSAGEBIRD_ACCESS_KEY: Your Live API key.
    • MESSAGEBIRD_ORIGINATOR: Your chosen sender ID/number.
    • Ensure these variables are available to the "Production" environment (and optionally "Preview" and "Development" if needed). Do not mark them as "Exposed to Browser".
  4. Deploy: Trigger a deployment (usually automatic on push to the main branch).

Other Platforms (Netlify, AWS Amplify, Docker, Node Server):

  • The process is similar: build your Next.js application (npm run build) and deploy the output (.next directory, public, package.json, etc.).
  • The key difference is how you manage environment variables. Consult your platform's documentation for securely setting server-side environment variables for MESSAGEBIRD_ACCESS_KEY and MESSAGEBIRD_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:

    • Form Submission: Can you successfully enter a recipient number and message and click "Send SMS"?
    • Frontend Feedback (Success): Does the form show a success message after a successful send attempt?
    • Frontend Feedback (Error): Does the form show an appropriate error message if you enter invalid data (e.g., missing recipient) or if the API call fails?
    • SMS Reception: Does the test message arrive on the recipient's phone?
    • Originator Check: Does the received SMS show the correct originator (your configured number or sender ID)?
    • API Route Logs (Server/Deployment Platform): Can you access server logs to confirm the API route is being hit and see the MessageBird success/error logs?
    • MessageBird Message Logs: Does the sent message appear correctly in the MessageBird dashboard message logs with a sent or delivered status? Check for failed status and reasons.
    • Environment Variables: Confirm environment variables are correctly configured in the deployment environment (Vercel settings, etc.) and not exposed to the browser.
    • Basic Input Validation Test: Try sending without a recipient or message – does the API return a 400 Bad Request?
    • Security Check: Ensure .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:

  • Adding robust input validation using libraries like libphonenumber-js for phone numbers.
  • Implementing authentication to protect the sending functionality so only logged-in users can access it.
  • Building a UI for message history by querying MessageBird logs via their API or storing sent message details in your own database.
  • Handling inbound messages by setting up webhooks in MessageBird to receive replies or incoming messages to your virtual number.
  • Scheduling messages using a database and a background job runner (like BullMQ with Redis, or a serverless scheduler like Vercel Cron Jobs) to send messages at a future time.
  • Adding templates for creating reusable message templates for common notifications.

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!

Frequently Asked Questions

How to send SMS with MessageBird in Next.js?

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.

What is the MessageBird Node.js SDK?

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.

Why use Next.js API routes for SMS sending?

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.

When should I use an alphanumeric sender ID with MessageBird?

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.

How to set up MessageBird API key in Next.js?

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.

What is the purpose of the originator in MessageBird?

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.

How to handle errors when sending SMS via MessageBird?

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.

What is the correct phone number format for MessageBird?

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.

How to improve security when sending SMS with Next.js and MessageBird?

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.

Can I see the SMS message logs in MessageBird?

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.

How do I handle inbound SMS messages with MessageBird and Next.js?

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.

What are some next steps after implementing basic SMS sending with Next.js?

Enhance your application by adding input validation, user authentication, message history tracking, or implementing inbound message handling using MessageBird webhooks.