Bulk SMS

MessageBird SMS Marketing Campaign Tutorial: Node.js, Express & MongoDB Implementation

Learn how to build compliant SMS marketing campaigns with MessageBird API, Node.js, and Express. Complete guide covering subscriber opt-in/opt-out, broadcast messaging, MongoDB integration, and TCPA/GDPR compliance.

JH
Jacky Hossein
β€’ Principal Telecommunications Architect β€’ Published Nov 2, 2026 β€’ 14 min read

Developer Quick-Start: Learn how to build compliant SMS marketing campaigns with MessageBird API, Node.js, and Express. Complete guide covering subscriber opt-in/opt-out, broadcast messaging, MongoDB integration, and TCPA/GDPR compliance. Want to skip 10DLC vetting queues, carrier surcharges, and multi-step SDK boilerplate? You can send the same SMS directly via SMSRoute's REST API with instant no-KYC provisioning.

⚠️ Important: This guide covers Express.js and MongoDB. The filename references Next.js and Supabase but the implementation uses Express and MongoDB stack.

πŸ”’ Security Notice: This guide includes authentication placeholders. Implement proper authentication before deploying to production. Never expose admin endpoints without authentication.

βš–οΈ Compliance Warning: Ensure compliance with local SMS marketing regulations (TCPA in the US, GDPR in the EU, CTIA guidelines). This guide provides technical implementation, not legal advice. Consult legal counsel for compliance requirements in your jurisdiction.

Build a production-ready SMS marketing campaign application using Node.js, Express, and the MessageBird API. This comprehensive tutorial shows you how to implement compliant SMS marketing with subscriber opt-in/opt-out management, broadcast messaging, and MongoDB database integration.

Learn how to create an SMS subscription system where customers can text "SUBSCRIBE" or "STOP" to manage their preferences, while administrators send targeted marketing campaigns through a web interface. This guide covers MessageBird API integration, webhook handling for inbound SMS, database design for subscriber management, and compliance with TCPA and GDPR regulations.

Key Features:

  • User opt-in via SUBSCRIBE keyword
  • User opt-out via STOP keyword
  • Confirmation messages for subscription changes
  • Admin interface to send broadcast messages
  • Database storage for subscribers

Technology Stack:

  • Node.js: JavaScript runtime environment (v14+ recommended)
  • Express: Web application framework for Node.js (v4.18+)
  • MessageBird: Communications Platform as a Service (CPaaS) for sending/receiving SMS
  • MongoDB: NoSQL database for storing subscriber information (v4.4+)
  • dotenv: Module to load environment variables from a .env file

Note: Development tools like localtunnel help test webhooks locally but aren't part of the production stack.

System Architecture:

graph LR
    UserMobile -- SMS (SUBSCRIBE/STOP) --> MessageBirdVMN[MessageBird Virtual Number]
    MessageBirdVMN -- Webhook --> ExpressApp[Node.js/Express App]
    ExpressApp -- DB Query/Update --> MongoDB[MongoDB Database]
    ExpressApp -- Send Confirmation SMS --> MessageBirdAPI[MessageBird API]
    MessageBirdAPI -- SMS --> UserMobile

    AdminBrowser -- HTTP Request --> ExpressApp
    ExpressApp -- DB Query (Get Subscribers) --> MongoDB
    ExpressApp -- Send Broadcast SMS --> MessageBirdAPI
    MessageBirdAPI -- SMS --> ActiveSubscribers[Subscribed User Mobiles]

Prerequisites:

  • Node.js and npm: Install v14 or later from nodejs.org
  • Git: For cloning repositories (optional)
  • MessageBird Account: Sign up for free at messagebird.com
  • MongoDB Instance: A running MongoDB server v4.4+ (local or cloud-based like MongoDB Atlas). Obtain the connection string (URI)
  • A Mobile Phone: For testing SMS sending and receiving

1. Set Up Your Node.js SMS Marketing Project

Initialize the project, install dependencies, and set up the basic structure.

  1. Create Project Directory: Open your terminal and create a new directory for the project, then navigate into it.
   mkdir node-messagebird-campaign
   cd node-messagebird-campaign
  1. Initialize Node.js Project: Create a package.json file.
   npm init -y
  1. Install Dependencies: Install Express for the web server, the MessageBird SDK, the MongoDB driver, and dotenv for managing environment variables.
   npm install express messagebird mongodb dotenv
  1. Create Project Files: Create the main application file, environment file example, and a .gitignore file.
   touch index.js .env .env.example .gitignore
  1. Configure .gitignore: Prevent sensitive files and generated folders from being committed to version control. Add the following to .gitignore:
   # Environment variables
   .env

   # Node dependencies
   node_modules/

   # Log files
   *.log
  1. Set Up Environment Variables (.env.example and .env): Define the structure in .env.example. This file can be committed safely.

ini

   MESSAGEBIRD_API_KEY=YOUR_MESSAGEBIRD_LIVE_API_KEY
   MESSAGEBIRD_ORIGINATOR=YOUR_MESSAGEBIRD_VIRTUAL_NUMBER_OR_SENDER_ID

   MONGODB_URI=YOUR_MONGODB_CONNECTION_STRING

   PORT=8080

Now, create your actual .env file by copying .env.example. Never commit .env to Git. Fill it with your actual credentials (obtain these in the next steps).

   cp .env.example .env
  • MESSAGEBIRD\_API\_KEY: Your Live API key from the MessageBird Dashboard
  • MESSAGEBIRD\_ORIGINATOR: The virtual mobile number (VMN) you purchase from MessageBird (in E.164 format, e.g., +12025550135) or an alphanumeric Sender ID (if supported in your target countries). You'll obtain this soon.
  • MONGODB\_URI: Your MongoDB connection string (e.g., mongodb://localhost:27017/sms\_campaign)
  • PORT: The port your application will run on (defaults to 8080)
  1. Create Basic Express Server (index.js): Set up the initial Express application structure.
   require('dotenv').config();
   const express = require('express');
   const { MongoClient } = require('mongodb');
   const messagebird = require('messagebird')(process.env.MESSAGEBIRD_API_KEY);

   const app = express();
   const port = process.env.PORT || 8080;

   app.use(express.urlencoded({ extended: true }));

   app.use(express.json());

   let db;
   const SUBSCRIBERS_COLLECTION = 'subscribers';

   async function connectDB() {
     try {
       const client = new MongoClient(process.env.MONGODB_URI);
       await client.connect();
       db = client.db();
       console.log("Successfully connected to MongoDB.");


       await db.collection(SUBSCRIBERS_COLLECTION).createIndex({ number: 1 }, { unique: true });
       console.log(`Index on 'number' in '${SUBSCRIBERS_COLLECTION}' collection ensured.`);

     } catch (err) {
       console.error("Failed to connect to MongoDB or ensure index", err);
       process.exit(1);
     }
   }

   connectDB().then(() => {
     app.listen(port, () => {
       console.log(`Server listening at http://localhost:${port}`);
     });
   });

You've now set up the basic project structure, dependencies, environment variable handling, a simple Express server, and initial database connection logic including index creation.

2. Configure MessageBird API for SMS Marketing

Set up your MessageBird account to send SMS campaigns and receive subscriber responses through webhooks.

  1. Obtain MessageBird API Key:
  • Log in to your MessageBird Dashboard
  • Navigate to Developers > API access
  • If you don't have a LIVE API key, click "Add access key"
  • Copy the Live API Key
  • Paste this key into your .env file as MESSAGEBIRD\_API\_KEY
  1. Purchase a Virtual Mobile Number (VMN): You need a dedicated number to receive incoming messages (SUBSCRIBE/STOP).
  • In the MessageBird Dashboard, go to Numbers
  • Click Buy a number
  • Select your desired country
  • Ensure the SMS capability is checked
  • Choose a number from the list
  • Select the billing duration and confirm the purchase
  • Copy the purchased number (in E.164 format, e.g., +12025550135)
  • Paste this number into your .env file as MESSAGEBIRD\_ORIGINATOR. This will also be the sender ID for outgoing messages.

Note: Some countries support alphanumeric sender IDs (e.g., "MyBrand"). If using one, ensure it's compliant and supported. For receiving messages, you must use a number.

  1. Set Up Localtunnel for Webhook Testing: MessageBird needs a publicly accessible URL to send incoming message notifications (webhooks). During development, localtunnel exposes your local server.
  • Install localtunnel globally:
     npm install -g localtunnel
  • Run your Node.js application (ensure it runs on the port specified in .env, e.g., 8080):
     node index.js
  • Open a new terminal window/tab in the same project directory
  • Start localtunnel, pointing it to your local application port:
     lt --port 8080
  • localtunnel will output a public URL (e.g., https://your-subdomain.loca.lt). Copy this URL. You'll need it in the next step. Keep this tunnel running during testing. Note: This URL changes every time you restart localtunnel unless you use advanced options.
  1. Configure MessageBird Flow Builder for Incoming Messages: Connect your purchased VMN to your application's webhook endpoint.
  • Go back to the Numbers section in the MessageBird Dashboard
  • Find the number you purchased and click the Flow icon (looks like connected dots) next to it, or click "Attach flow"
  • Select Create Custom Flow
  • Give your flow a descriptive name (e.g., "SMS Campaign Handler")
  • Choose SMS as the trigger. Click Next
  • The flow editor will open with the "SMS" step already added. Click the + button below it
  • Choose Forward to URL as the next step
  • Set the Method to POST
  • In the URL field, paste the localtunnel URL you copied, and append /webhook (e.g., https://your-subdomain.loca.lt/webhook). This is the route you'll define in Express to handle incoming messages
  • Click Save
  • Click Publish (top right) to activate the flow

Your flow should look like: SMS β†’ Forward to URL. Now, when someone sends an SMS to your VMN, MessageBird forwards the details to your application's /webhook endpoint via a POST request.

3. Build SMS Subscriber Opt-In/Opt-Out Management

Implement the database layer and webhook endpoint to handle SMS subscription commands like SUBSCRIBE and STOP.

  1. Add Database Helper Functions (index.js): Add functions to interact with the subscribers collection in MongoDB.
   async function findSubscriber(number) {
     if (!db) throw new Error("Database not connected");
     return db.collection(SUBSCRIBERS_COLLECTION).findOne({ number: number });
   }

   async function addOrUpdateSubscriber(number) {
     if (!db) throw new Error("Database not connected");
     return db.collection(SUBSCRIBERS_COLLECTION).updateOne(
       { number: number },
       { $set: { number: number, subscribed: true, updatedAt: new Date() } },
       { upsert: true }
     );
   }

   async function updateSubscriberStatus(number, status) {
     if (!db) throw new Error("Database not connected");
     return db.collection(SUBSCRIBERS_COLLECTION).updateOne(
       { number: number },
       { $set: { subscribed: status, updatedAt: new Date() } }
     );
   }

   async function getActiveSubscribers() {
     if (!db) throw new Error("Database not connected");
     return db.collection(SUBSCRIBERS_COLLECTION).find({ subscribed: true }).toArray();
   }

   async function sendSms(recipient, body) {
       const params = {
           originator: process.env.MESSAGEBIRD_ORIGINATOR,
           recipients: [recipient],
           body: body,
       };

       try {
           console.log(`Sending SMS to ${recipient}: "${body}"`);
           const response = await messagebird.messages.create(params);
           console.log(`MessageBird response for ${recipient}: Status ${response.recipients.items[0].status}`);
           return response;
       } catch (error) {
           console.error(`MessageBird API Error sending to ${recipient}:`, error);
           throw error;
       }
   }
  1. Create Webhook Handler (index.js): Create the /webhook route to process incoming SMS messages from MessageBird.
   app.post('/webhook', async (req, res) => {

     const { originator, payload } = req.body;
     if (!originator || payload === undefined) {
       console.warn('Received incomplete webhook payload:', req.body);
       return res.sendStatus(400);
     }

     const command = payload.trim().toLowerCase();
     console.log(`Received command '${command}' from ${originator}`);

     try {

       const subscriber = await findSubscriber(originator);


       if (command === 'subscribe') {
         if (subscriber && subscriber.subscribed) {
           console.log(`${originator} is already subscribed.`);


         } else {
           await addOrUpdateSubscriber(originator);
           console.log(`Subscribed ${originator}`);
           await sendSms(originator, 'Thanks for subscribing! Text STOP anytime to unsubscribe.');
         }
       } else if (command === 'stop') {
         if (!subscriber || !subscriber.subscribed) {
           console.log(`${originator} is not currently subscribed.`);


         } else {
           await updateSubscriberStatus(originator, false);
           console.log(`Unsubscribed ${originator}`);
           await sendSms(originator, 'You have been unsubscribed. Text SUBSCRIBE to join again.');
         }
       } else {

         console.log(`Ignoring unknown command '${command}' from ${originator}`);


       }


       res.sendStatus(200);

     } catch (error) {
       console.error(`Error processing webhook for ${originator}:`, error);
       res.sendStatus(500);
     }
   });

This route extracts the sender's number (originator) and message content (payload), converts the command to lowercase, checks the database, updates the subscriber's status accordingly, and sends a confirmation SMS. It then sends a 200 OK status back to MessageBird to acknowledge receipt.

4. Create Admin Interface for SMS Broadcast Campaigns

πŸ”’ Security Critical: Implement authentication before deploying these routes to production.

Build a web-based admin panel for sending SMS broadcast messages to your subscriber list.

  1. Add Admin Form Route (index.js): Add a GET route to display the HTML form. Secure this route before production deployment.
   app.get('/', async (req, res) => {
     try {
       const activeSubscribers = await getActiveSubscribers();
       const subscriberCount = activeSubscribers.length;


       res.send(`
         <!DOCTYPE html>
         <html lang="en">
         <head>
           <meta charset="UTF-8">
           <meta name="viewport" content="width=device-width, initial-scale=1.0">
           <title>SMS Campaign Admin</title>
           <style>
             body { font-family: sans-serif; padding: 20px; max-width: 800px; margin: auto; }
             textarea { width: 100%; min-height: 100px; margin-bottom: 10px; box-sizing: border-box; padding: 8px; border: 1px solid #ccc; border-radius: 4px; }
             button { padding: 10px 20px; cursor: pointer; background-color: #007bff; color: white; border: none; border-radius: 4px; }
             button:hover { background-color: #0056b3; }
             .status { margin-top: 20px; padding: 10px; background-color: #f0f0f0; border: 1px solid #ccc; border-radius: 4px; }
             pre { background-color: #eee; padding: 10px; border: 1px solid #ccc; white-space: pre-wrap; word-wrap: break-word; border-radius: 4px; }
             label { display: block; margin-bottom: 5px; font-weight: bold; }
           </style>
         </head>
         <body>
           <h1>Send Broadcast SMS</h1>
           <p>Current active subscribers: <strong>${subscriberCount}</strong></p>
           <form action="/send" method="POST">
             <div>
               <label for="message">Message:</label>
               <textarea id="message" name="message" required></textarea>
             </div>
             <button type="submit">Send to Subscribers</button>
           </form>
           <div id="status" class="status" style="display: none;"></div>
           <script>
             const form = document.querySelector('form');
             const statusDiv = document.getElementById('status');
             if (form && statusDiv) {
                 form.addEventListener('submit', function(event) {
                     statusDiv.style.display = 'block';
                     statusDiv.textContent = 'Sending... please wait.';
                 });
             }
           </script>
         </body>
         </html>
       `);
     } catch (error) {
       console.error("Error loading admin page:", error);
       res.status(500).send("Error loading admin page.");
     }
   });
  1. Add Broadcast Sending Route (index.js): Add a POST route to handle the form submission and send the broadcast. Secure this route before production deployment.
   app.post('/send', async (req, res) => {
     const messageBody = req.body.message;
     if (!messageBody || messageBody.trim() === '') {
       return res.status(400).send("Message body cannot be empty.");
     }

     try {
       const subscribers = await getActiveSubscribers();
       if (subscribers.length === 0) {
         return res.send(`
           <!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Broadcast Result</title><style>body{font-family:sans-serif;padding:20px;}</style></head><body>
           <h1>Broadcast Result</h1>
           <p>No active subscribers to send to.</p>
           <a href="/">Back to Admin</a>
           </body></html>
         `);
       }

       const recipients = subscribers.map(sub => sub.number);
       console.log(`Attempting to send broadcast to ${recipients.length} recipients.`);



       const batchSize = 50;
       let successfulSends = 0;
       let failedSends = 0;
       const totalRecipients = recipients.length;

       for (let i = 0; i < totalRecipients; i += batchSize) {
         const batch = recipients.slice(i, i + batchSize);
         const params = {
           originator: process.env.MESSAGEBIRD_ORIGINATOR,
           recipients: batch,
           body: messageBody,
         };

         try {
             console.log(`Sending batch ${Math.floor(i / batchSize) + 1}/${Math.ceil(totalRecipients / batchSize)} (${batch.length} recipients)...`);
             const response = await messagebird.messages.create(params);
             const sentInBatch = response.recipients.totalSentCount || batch.length;
             successfulSends += sentInBatch;
             console.log(`Batch ${Math.floor(i / batchSize) + 1} queued. Response indicates ~${sentInBatch} sent.`);
         } catch (batchError) {
             console.error(`Error sending batch starting at index ${i}:`, batchError);
             failedSends += batch.length;
         }
       }

       console.log(`Broadcast finished. Attempted: ${totalRecipients}, Queued (estimated): ${successfulSends}, Failed Batches (estimated): ${failedSends}`);


       res.send(`
         <!DOCTYPE html>
         <html lang="en">
         <head>
           <meta charset="UTF-8">
           <title>Broadcast Result</title>
           <style>
             body { font-family: sans-serif; padding: 20px; max-width: 800px; margin: auto; }
             pre { background-color: #eee; padding: 10px; border: 1px solid #ccc; white-space: pre-wrap; word-wrap: break-word; border-radius: 4px; }
             .error { color: red; font-weight: bold; }
             a { color: #007bff; text-decoration: none; }
             a:hover { text-decoration: underline; }
           </style>
         </head>
         <body>
           <h1>Broadcast Result</h1>
           <p>Message queuing initiated for approximately ${successfulSends} out of ${totalRecipients} active subscribers.</p>
           ${failedSends > 0 ? `<p class="error">Failed to queue messages for ${failedSends} recipients due to batch errors. Check server logs for details.</p>` : ''}
           <hr>
           <p><strong>Message Sent:</strong></p>
           <pre id="message-sent"></pre>
           <a href="/">Back to Admin</a>

           <script>
             const messageBody = ${JSON.stringify(messageBody)};
             const preTag = document.getElementById('message-sent');
             if (preTag) {
                 preTag.textContent = messageBody;
             }
           </script>
         </body>
         </html>
       `);

     } catch (error) {
       console.error("Error sending broadcast:", error);
       res.status(500).send(`
           <!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Broadcast Failed</title><style>body{font-family:sans-serif;padding:20px;}</style></head><body>
           <h1>Broadcast Failed</h1>
           <p>An internal error occurred while trying to send the broadcast. Check server logs.</p>
           <a href="/">Back to Admin</a>
           </body></html>
         `);
     }
   });

This route retrieves active subscribers, batches them (max 50 per request), uses async/await with messagebird.messages.create for each batch, and provides feedback.

5. Implement Error Handling and Logging for SMS Operations

Robust handling is crucial for production.

  • Database Connection: The connectDB function handles initial connection errors.
  • Webhook Errors: The /webhook route uses try...catch. Log errors server-side. Respond 200 OK to MessageBird unless you want retries for specific, transient errors.
  • Broadcast Errors: The /send route uses try...catch for overall errors and within the batch loop. Log errors and provide admin feedback.
  • Logging: console.\* is basic. Integrate a structured logging library like Winston or Pino:
  npm install winston

Conceptual Winston Setup:

  const winston = require('winston');

  const logger = winston.createLogger({
    level: 'info',
    format: winston.format.combine(
      winston.format.timestamp(),
      winston.format.json()
    ),
    transports: [

      new winston.transports.File({ filename: 'error.log', level: 'error' }),

      new winston.transports.File({ filename: 'combined.log' }),
    ],
  });

  if (process.env.NODE_ENV !== 'production') {
    logger.add(new winston.transports.Console({
      format: winston.format.simple(),
    }));
  }

  module.exports = logger;
  • Retries: For critical operations like sending SMS, implement retries for transient errors (network issues, temporary API limits). Libraries like async-retry can help. Conceptual Retry for sendSms:

JavaScript (Full integration of advanced logging and retries requires careful setup beyond this core guide but is highly recommended.)

6. Design MongoDB Schema for SMS Subscriber Management

  • Schema: We use a simple MongoDB document structure in the subscribers collection:
  {
    ""_id"": ""ObjectId(...)"",
    ""number"": ""+12025550135"",
    ""subscribed"": true,
    ""updatedAt"": ""ISODate(...)""
  }
  • \_id: Auto-generated by MongoDB.
  • number: Subscriber phone number (E.164 format) - Indexed, Unique.
  • subscribed: Boolean indicating opt-in status.
  • updatedAt: Timestamp of last status change.
  • Indexing: A unique index on the number field is crucial for performance and data integrity. This is now automatically created or verified on application startup within the connectDB function.
  • Data Layer: The helper functions (findSubscriber, addOrUpdateSubscriber, etc.) provide a basic data access layer, abstracting database operations.

7. Implement Security Best Practices for SMS Marketing

  • Input Validation/Sanitization:
  • Webhook: We trim() and toLowerCase() commands. The originator format is generally reliable from MessageBird.
  • Admin Form: The message body is used. The result page now uses textContent for safer display. Validate message length/content server-side.
  • Protect Admin Endpoints: The / (admin form) and /send (broadcast action) routes must be protected. Implement authentication and authorization. This is critical for production.
  • Strategies: Session-based auth (using express-session and a login form), JSON Web Tokens (JWT), Basic Authentication (less secure, suitable only for internal tools with HTTPS), or OAuth integration.
  • Conceptual Middleware:
    function ensureAuthenticated(req, res, next) {




      const isAuthenticated = false;

      if (isAuthenticated) {
        return next();
      } else {




        res.status(401).send('Unauthorized: Please log in.');
      }
    }

    app.get('/', ensureAuthenticated, async (req, res) => {  });
    app.post('/send', ensureAuthenticated, async (req, res) => {  });
  • Rate Limiting:
  • Webhooks: Use express-rate-limit on /webhook to prevent abuse.
  • Admin: Apply rate limiting to /send and login endpoints.
  npm install express-rate-limit

Conceptual Rate Limiting: JavaScript

8. Handle Edge Cases in SMS Subscription Management

  • Case Insensitivity: Handled via .toLowerCase() for commands.
  • Duplicate Subscriptions: addOrUpdateSubscriber handles this gracefully via upsert.
  • Unsubscribe Non-subscriber: Logic checks state before unsubscribing.
  • Unknown Commands: Ignored; optionally send a help message.
  • Number Formatting: Assumes E.164 from MessageBird.
  • Internationalization: Requires storing language preferences and loading localized templates/messages.

9. Optimize SMS Campaign Performance and Delivery

  • Database Indexing: Unique index on number is implemented.
  • Batch Sending: Implemented in /send (50 recipients/request).
  • Asynchronous Operations: async/await used for non-blocking I/O.
  • Load Testing: Use tools like k6, Artillery to test /webhook and /send under load.
  • Caching: Consider Redis for caching active subscribers in high-read scenarios, ensuring proper cache invalidation on subscription changes.

10. Monitor SMS Campaign Delivery and Performance

  • Health Checks: Add a robust health check endpoint. Using a database ping command is more reliable than just checking the connection variable.
  app.get('/health', async (req, res) => {
    try {
      if (!db) {
        throw new Error('Database connection not established');
      }

      await db.admin().ping();
      res.status(200).send('OK');
    } catch (error) {
      console.error("Health check failed:", error);
      res.status(503).send('Service Unavailable - DB Connection issue');
    }
  });
  • Logging: Centralized, structured logging (Section 5).
  • Metrics: Use libraries like prom-client to expose Prometheus metrics (request counts, latency, errors).
  • Error Tracking: Integrate services like Sentry, Bugsnag, or Datadog APM for real-time error reporting and analysis.
  • MessageBird Dashboard: Monitor SMS delivery rates, errors, and costs directly within the MessageBird platform.

11. Troubleshoot Common MessageBird SMS Issues

  • Webhook Not Firing: Check localtunnel status/URL, ensure your Node.js server is running and accessible, check server logs for errors on startup or during requests, verify firewall settings, and review the MessageBird Flow Builder logs for errors or delivery attempts.
  • Messages Not Sending: Verify MESSAGEBIRD\_API\_KEY and MESSAGEBIRD\_ORIGINATOR in .env, check MessageBird account balance/credits, ensure recipient numbers are valid E.164 format, check server logs for API errors from the sendSms function, and look at MessageBird Dashboard logs for delivery status.
  • Database Errors: Ensure MongoDB is running and accessible, verify the MONGODB\_URI is correct, check database server logs, and monitor database performance. The unique index prevents duplicate numbers but errors during upsert should be logged.
  • Localtunnel Instability: localtunnel URLs can change or tunnels can drop. For more stable development, consider ngrok or deploying to a staging environment with a permanent URL. For production, deploy to a hosting provider (PaaS like Heroku/Render, or IaaS like AWS/GCP/Azure) with a public IP/domain.
  • Rate Limits: Be aware of MessageBird API rate limits and your own application's rate limits (Section 7). Implement backoff/retry strategies (Section 5).

For additional MessageBird SMS tutorials and guides, check out:

  • Send SMS with MessageBird and Node.js - Basic SMS sending guide
  • MessageBird Two-Way SMS Messaging - Build interactive SMS conversations
  • MessageBird SMS OTP and 2FA - Implement SMS authentication

Questions? Contact MessageBird support or explore the MessageBird Developer Documentation for comprehensive API references and additional SMS marketing resources.

Simpler Alternative: Send the Same SMS With SMSRoute (No-KYC, Direct Routes)

If you want to replace legacy aggregator SDK boilerplate, multi-week compliance queues, and opaque carrier surcharges with a single HTTP request, SMSRoute delivers global SMS over direct Tier-1 carrier interconnects with instant API access and transparent per-country pricing.

curl -X POST https://api.sendsmsnokyc.com/messages \
  -H "x-api-key: $SMSROUTE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "to": ["+14155551234"],
    "channel": ["sms"],
    "body": "Your verification code is 482910"
  }'
  • Instant onboarding: No KYC paperwork or sales queues β€” grab an API key and fund with crypto (BTC/USDT) or card.
  • Direct Tier-1 routes: Verify real handset delivery, DLR latency, and Sender ID preservation before launch via SMSRoute Live Carrier Testing.
  • Transparent global pricing: Compare exact per-country termination rates on our live pricing page.

Ship Global SMS in One API Call

Skip legacy SDK sprawl and carrier bottlenecks. Send OTPs, alerts, and bulk campaigns across 190+ countries with SMSRoute.

Explore SMSRoute Developers β†’