For Sales Query Call: +44 7882972645
API Integration

How to Integrate SMS API in Node.js: The Complete JavaScript Developer Handbook

Jun 30, 2026 1,150 Views
How to Integrate SMS API in Node.js: The Complete JavaScript Developer Handbook

Introduction: Powering Node.js Real-Time Services with SMS

Node.js is renowned for its non-blocking, event-driven architecture, making it the premier choice for building highly scalable network applications, RESTful APIs, chat engines, and microservice backends. In these real-time systems, communication must keep pace with processing speeds. Triggering notifications, alerts, and transactional messages directly from your JavaScript backend is essential for providing an interactive user experience.

Integrating a direct gateway communication channel via a SMS API Node.js Example is a simple process. Leveraging Node's asynchronous features allows you to trigger messages without blocking other active connections on your application server. This guide covers how to write asynchronous SMS request modules using popular npm HTTP clients (like Axios), native Node.js HTTPS libraries (for zero-dependency setups), and Express.js webhooks to handle real-time delivery reports.

Prerequisites: Getting Started

To begin integration, make sure you have the following requirements completed:

  • Node.js Environment: Node.js version 14.x or higher installed, along with npm (Node Package Manager).
  • API Token: Sign up for an account on BlackSMS and fetch your secure API key from your settings dashboard.
  • DLT Meta Data (India): If your destination numbers are inside India, obtain your approved Principal Entity ID (PE ID) and Template IDs from your DLT portal.

Method 1: Node.js SMS Integration using Axios

Axios is the most widely used promise-based HTTP client for JavaScript applications. To install it, run npm install axios in your project directory. The following code shows how to write a simple async/await function to dispatch an SMS:

const axios = require('axios');

async function sendSMS() {
    const apiUrl = 'https://api.blacksms.in/v1/send';
    const apiKey = 'YOUR_SECURE_API_KEY';

    const payload = {
        api_key: apiKey,
        sender_id: 'BLKSMS',
        phone: '919876543210',
        message: 'Dear User, 123456 is your security verification code for BlackSMS.',
        pe_id: '1201159123456789012', // DLT Entity ID (India)
        template_id: '1207161712345678901' // DLT Approved Template ID
    };

    try {
        const response = await axios.post(apiUrl, payload, {
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            },
            timeout: 8000 // 8-second request timeout
        });

        if (response.status === 200 && response.data.status === 'success') {
            console.log(`SMS Sent Successfully! Message ID: ${response.data.message_id}`);
        } else {
            console.error('Failed to send SMS:', response.data.message || 'Unknown Error');
        }
    } catch (error) {
        if (error.response) {
            // The request was made and server responded with a status code outside of 2xx
            console.error(`API Error (HTTP ${error.response.status}):`, error.response.data);
        } else if (error.request) {
            // The request was made but no response was received
            console.error('Network Error: No response received from SMS gateway');
        } else {
            // Something else went wrong setting up the request
            console.error('Error:', error.message);
        }
    }
}

sendSMS();

Method 2: Zero-Dependency SMS using Native Node.js HTTPS Module

In serverless execution environments (like AWS Lambda, Google Cloud Functions, or Vercel Edge functions), keeping package sizes small is essential for fast cold-start times. For these scenarios, you can send requests without using external libraries by using Node's built-in https module. Here is how to implement it:

const https = require('https');

function sendNativeSMS(phone, message, templateId, peId = '') {
    return new Promise((resolve, reject) => {
        const apiUrl = new URL('https://api.blacksms.in/v1/send');
        const payload = JSON.stringify({
            api_key: 'YOUR_SECURE_API_KEY',
            sender_id: 'BLKSMS',
            phone: phone,
            message: message,
            template_id: templateId,
            pe_id: peId
        });

        const options = {
            hostname: apiUrl.hostname,
            path: apiUrl.pathname,
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Content-Length': Buffer.byteLength(payload),
                'Accept': 'application/json'
            },
            timeout: 8000
        };

        const req = https.request(options, (res) => {
            let data = '';
            res.on('data', (chunk) => { data += chunk; });
            res.on('end', () => {
                try {
                    const parsed = JSON.parse(data);
                    if (res.statusCode === 200 && parsed.status === 'success') {
                        resolve({ success: true, messageId: parsed.message_id });
                    } else {
                        resolve({ success: false, error: parsed.message || 'API Error', statusCode: res.statusCode });
                    }
                } catch (e) {
                    reject(new Error('Failed to parse gateway response JSON'));
                }
            });
        });

        req.on('error', (err) => { reject(err); });
        req.on('timeout', () => {
            req.destroy();
            reject(new Error('SMS Gateway Connection Timed Out'));
        });

        req.write(payload);
        req.end();
    });
}

// Usage Example:
sendNativeSMS('919876543210', 'Dear User, 123456...', '1207161712345678901', '1201159123456789012')
    .then(res => console.log(res))
    .catch(err => console.error(err));

Setting Up a Webhook Listener in Node.js (Express)

To capture status reports (DLR) pushed by the BlackSMS gateway, setup an endpoint inside your Express server. First, make sure express is installed (npm install express). The following script parses incoming status notifications and updates your application data:

const express = require('express');
const app = express();

// Middleware to parse incoming JSON bodies
app.use(express.json());

app.post('/webhooks/sms-delivery', (req, res) => {
    const { message_id, status, phone, delivered_at } = req.body;

    if (!message_id || !status) {
        return res.status(400).json({ error: 'Missing required parameters' });
    }

    console.log(`Received status callback: Message ${message_id} to ${phone} status is: ${status}`);

    // TODO: Update status in your database
    // Example: db.query('UPDATE sms_logs SET status = ? WHERE id = ?', [status, message_id])

    // Acknowledge receipt of the webhook
    res.status(200).json({ status: 'acknowledged' });
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(`Webhook server is listening on port ${PORT}`);
});

Best Practices for Asynchronous SMS Processing

To ensure high performance and application stability when processing SMS requests in JavaScript, implement these design patterns:

  1. Offload to queues for bulk tasks: Avoid looping through arrays of thousands of phone numbers and triggering thousands of HTTP connections simultaneously. This can exhaust the local socket pool. Instead, use job queues (such as BullMQ or Bee-Queue) powered by Redis to process dispatches sequentially in the background.
  2. Format phone numbers programmatically: Clean input strings to prevent API failures. Remove non-numeric characters using regex (phone.replace(/\D/g, '')) and verify the country prefix is attached.
  3. Handle Timeouts and Connection Breaks: Always set explicit timeouts on HTTP connections (typically 5 to 10 seconds). This prevents your Node.js processes from hanging indefinitely if the gateway experiences routing hiccups or operator lags.

Conclusion: Fast and Scalable Integrations

Integrating SMS delivery into a Node.js project is an efficient way to keep users informed in real-time. By leveraging asynchronous coding practices and choosing the right HTTP client, you can manage critical notifications without impacting your application's responsiveness. Integrating Express webhooks ensures your backend remains updated with real-time delivery status reports. BlackSMS provides low-latency REST APIs designed to support fast JavaScript configurations. Establish your API integration today and scale your communications.

Chat on WhatsApp