Node.js SMS API Integration Guide

Complete guide to integrate SMS API with Node.js applications. Async/await examples, error handling, and best practices.

Node.js SMS API Integration Guide

Learn how to integrate SMS functionality into your Node.js applications using our REST API with modern JavaScript features.

Prerequisites

  • Node.js 12.0 or higher
  • npm package manager
  • Valid API key from OnlineSMSService
  • Basic knowledge of JavaScript and async/await

Installation

npm install axios
# or
npm install node-fetch

Basic Integration

Simple SMS Sending with Axios

const axios = require('axios');

// SMS Gateway Integration for Node.js
const sendSMS = async (to, message, sender = 'OTPSMS') => {
    try {
        const response = await axios.post('https://api.onlinesmsservice.com/send', {
            to: to,
            message: message,
            sender: sender,
            type: 'transactional'
        }, {
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${process.env.SMS_API_KEY}`
            }
        });
        
        console.log('SMS sent successfully:', response.data);
        return response.data;
    } catch (error) {
        console.error('Failed to send SMS:', error.response?.data || error.message);
        throw error;
    }
};

// Usage example
sendSMS('919876543210', 'Your OTP is: 123456');

Advanced Features

Bulk SMS with Promise.all

const sendBulkSMS = async (recipients, message) => {
    const promises = recipients.map(phone => 
        sendSMS(phone, message, 'BULK')
    );
    
    try {
        const results = await Promise.all(promises);
        console.log('All SMS sent successfully:', results);
        return results;
    } catch (error) {
        console.error('Some SMS failed to send:', error);
        throw error;
    }
};

// Usage
const recipients = ['919876543210', '919876543211', '919876543212'];
sendBulkSMS(recipients, 'Bulk message content');

Express.js Integration

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

app.use(express.json());

// OTP endpoint
app.post('/send-otp', async (req, res) => {
    try {
        const { phone } = req.body;
        const otp = Math.floor(100000 + Math.random() * 900000);
        
        await sendSMS(phone, `Your OTP is: ${otp}`, 'OTPSMS');
        
        res.json({
            success: true,
            message: 'OTP sent successfully',
            otp: otp // Remove this in production
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            message: 'Failed to send OTP',
            error: error.message
        });
    }
});

app.listen(3000, () => {
    console.log('Server running on port 3000');
});

Ready to Start Integrating SMS?

Get your API key and start sending SMS messages in minutes

Get API Key Try API Playground