How to send A2P SMS using Node.js

TechTalks How to Send SMS using Node.js
Share with

In today’s fast-paced world, communication is key. Whether you are a business owner or a marketer, with nearly 100% mobile user coverage and high open rates, SMS is still a great channel to drive engagements and user action.  

While you can build an A2P (Application-to-Person) messaging program using your preferred coding language and platform, Node.js is an excellent choice for building an A2P  SMS program due to its non-blocking, event-driven architecture which enables developers to build high-performance, scalable, and real-time applications.  

Node.js is built on the V8 JavaScript engine, which is known for its lightning-fast performance, making it ideal for handling high-volume SMS traffic. Moreover, Node.js comes with a built-in module called “HTTP,” which makes it easy to send HTTP requests and receive responses, enabling developers to interact with SMS gateway APIs seamlessly. Additionally, Node.js has an extensive range of open-source packages and libraries that can be used to simplify the SMS program’s development process, saving time and resources. With its robust and efficient features, Node.js is an excellent choice for building an A2P SMS program. 

Let’s understand how to build an A2P SMS gateway service using node.js in detail: 

What are the popular SMS APIs for NodeJS? 

Some of the most popular SMS APIs for NodeJS include EnableX, Twilio, Nexmo, and Sinch. These APIs allow developers to quickly integrate SMS into their applications, making it easy to send and receive messages. 

What is NodeJS and what are its features? 

NodeJS is a JavaScript runtime environment that allows you to run JavaScript code outside the browser. It is an open-source, cross-platform runtime environment for developing server-side and network applications. Its key features include event-driven, asynchronous I/O APIs, npm package manager, single-threaded programming model, and support for web sockets. 

Why NodeJS a preferred environment for SMS gateway development 

  • NodeJS uses an event-driven, non-blocking I/O model and is highly efficient and scalable, making it ideal for building real-time applications. 
  • It has a large and active community of developers who contribute useful packages and libraries that accelerate the development process. 
  • It is built on top of JavaScript, which is an easy to learn programming language. It provides a great combination of speed, efficiency, scalability, and flexibility. 

EnableX SMS API: why you should use it with NodeJS 

EnableX SMS APIs empowers communication conveniently and effectively in just a few lines with NodeJS. You can send SMS messages to any mobile phone number around the world, right from your Node.js application. It is incredibly useful for businesses that need to send notifications to their customers, clients, users or for individuals who want to stay connected. The process of sending an SMS message with NodeJS and EnableX is easy and straightforward.  

Prerequisites to send SMS with NodeJS and EnableX 

  • Create an account on EnableX Portal. If you are new to EnableX, Signup now 
  • Create SMS project 
  • Create and set up a Campaign 
  • Generate App ID and App key to access SMS API 
  • Buy a phone number from EnableX to send an SMS 
  • Install NodeJS on your machine 
  • Install NPM or another package manager 

To get started, you will need to sign up for an EnableX account and obtain an API key. Once you have your API key, you can use the EnableX API to send SMS messages directly from your NodeJS application. The API is well-documented and easy to use, so you can quickly get up and running with it. 

Send a test SMS with EnableX in just 4 steps 

  1. Sign up for the EnableX Portal 
  2. Subscribe to SMS Service 
  3. Go to the SMS Section and click Try Now 
  4. Use the default Campaign to send SMS 

How to send SMS through nodejs

How to Setup a Project with SMS Service 

You can create a new Project with SMS Service or add SMS Service to any existing Project. 

  • Login to EnableX portal 
  • Navigate to My Projects / Create Project 
  • Add Project Name and Select Application 
  • Enable SMS to include SMS capability in your Project 
  • Click on the CREATE PROJECT 

Send SMS using API

How to add SMS Service to an existing Project 

  • Navigate My Projects 
  • Click the Project name to which you wish to add SMS Service. You reach the Project Dashboard 
  • Or click the edit icon in front of the Project name to reach the Project Dashboard 
  • Navigate Services Subscribed 
  • On the Services Subscribed form, enable SMS to include SMS capability in your Project 
  • Click Save Changes  

How to create a campaign to send and receive SMS 

You need to create a campaign to send or receive SMS from your project’s SMS service. Sender IDs, numbers, message body templates, countries, etc., are just some of the settings you can choose when sending or receiving SMS. You can create your campaign in one of two ways. 

  1. Access the Dashboard by navigating to SMS (click My Projects on the side bar). Click the Create Campaign button to create your campaign. 
  2. Get access to your My Campaigns list by navigating to SMS (click My Projects on the side bar). 
  3. Click the Create Campaign button to create your campaign. 

How to setup a campaign for SMS 

  1. Select a Project from the list of available projects list, add a Campaign name, select your Country, select the required SMS Direction, and then select SMS Type. (Choose Promotional SMS for offers, discounts, and promotions and choose Transactional SMS for OTPs and alerts) 
  2. Send a quick test SMS to your trial account to get a code snippet for ready use or top up the wallet and upgrade your account to send more SMS. 
  3. For trial account users, the default Sender ID is ENABLX, and the default Template ID is Test Template. 
  4. You can use a Sender ID instead of your Phone Number in your outgoing SMSs and Template IDs are message templates that can be defined, saved, and reused. 
  5. SMS In Only campaigns must include a number, whether a long or a short code to receive SMS. 
  6. You can configure separate keywords against each of the campaigns. 
  7. For multiple campaigns on the same dedicated number, you can configure separate keywords for each to route the message to their respective Webhooks. 
  8. On the Final Test Run page, select Sender ID, add the recipient list in CSV format and select Send Now to test the incoming SMS flow. The code window displays the code. 

For more details, please click here. 

How to order Phone Numbers from EnableX (Long Code / Short Code) 

You can order a phone number from EnableX by selecting the country from where you like to get the phone number, choosing the service SMS for which you need the phone number, and entering the details of your request. 

How to buy number for sending A2P sms

How to use EnableX SMS API to send SMS  

EnableX provides SMS API which includes methods for sending messages, retrieving message delivery statuses, and managing contacts. By calling these methods, Node.js developers can integrate our SMS service into their own applications and services. 

Access SMS API with your project’s APP-ID and APP-KEY. Once authorized, you can then use the API to send out SMS messages to any number of recipients with the required message content. 

How to install EnableX SMS API package in NodeJS 

  • Run the following command from your terminal or command prompt to create a new directory for your project files on your computer 

mkdir node-enablex-sms-sample 

  • Install node packages 
  • npm install axios dotenv  btoa 
  • Change the directory into this new folder, initiate a new NodeJS project 
  • Create two new files inside node-enablex-sms-sample:sample.js and .env: 

touch sample.js .env
Get your EnableX account credentials and save to .env file 

How to authenticate with an SMS API using NodeJS?
Open your new .env file in your favourite text editor and add the following two empty variables: 

ENABLEX_APP_ID = 

ENABLEX_APP_KEY = 

Copy your APP-ID and add it as the value for the APP-ID environment variable. Likewise, copy your APP-KEY and add it as the value for the APP-KEY environment variable. 

Save and close your .env file.

How to send an SMS using NodeJS and EnableX 

 To send SMSs with NodeJS and EnableX, you need to use modules like Axios, HTTPS Request or fetch.  

If you use the axios module, you can call our API to send an SMS message using the following code snippet:  

const axios = require('axios'); 
const btoa = require('btoa'); 
require('dotenv').config(); 
 
const APP_ID = process.env.ENABLEX_APP_ID; 
const APP_KEY = process.env.ENABLEX_APP_KEY; 
const authKey = btoa(`${APP_ID}:${APP_KEY}`); 
 
const URL = "https://api.enablex.io/sms/v1/messages";   
const data = {  
    "from":" +44xxxxxxxx", //your EnableX configured phone number    
    "body": " {$name} you are due to pay Rs. {$amount} ",   
    "recipient": 
        {"to": +91xxxxxx","name": "Kamal","amount": "30" 
     ],  

    "type": "sms",   
    "reference": "XOXO",   
    "validity": "30",   
    "type_details": "",   
    "data_coding": "plain",   
    "flash_message": false,   
    "scheduled_dt": "2019-12-17T14:26:57+00:00",   
    "created_dt": "2019-12-15T14:26:57+00:00",   
    "campaign_id": "XX",   
    "template_id": "37081401"   
}; 

const options = {   
  headers: {   
    "Authorization": "Basic ${authKey}",   
    "Content-Type": "application/json"   
  }  
};  

axios.post(URL, data, options 
    .then((res) => 
        console.log("RESPONSE ==== : ", res);  
    })  
    .catch((err) => {   
        console.log ("ERROR: ====", err); 
    }) 

If you use the fetch module, you can call our API to send an SMS message using the following code snippet:  

const fetch = require("fetch" 
const btoa = require('btoa');  
require('dotenv').config();  

 
const APP_ID = process.env.ENABLEX_APP_ID 
const APP_KEY = process.env.ENABLEX_APP_KEY;   
const authKey = btoa(`${APP_ID}:${APP_KEY}`); 

 
const URL = "https://api.enablex.io/sms/v1/messages" 
const data = {  

    "from":"+44xxxxxxxx",   
    "body": "{$name} you are due to pay Rs. {$amount}",   
    "recipient": 
        {"to": "+91xxxxxx","name": "Kamal","amount": "30" 
     ],  
    "type": "sms",   
    "reference": "XOXO",   
    "validity": "30",   
    "type_details": "",   
    "data_coding": "plain",   
    "flash_message": false,   
    "scheduled_dt": "2019-12-17T14:26:57+00:00",   
    "created_dt": "2019-12-15T14:26:57+00:00",   
    "campaign_id": "XX",   
    "template_id": "37081401"   
}; 

fetch(URL, { 
    method: "POST", 
    body: JSON.stringify(data), 
    headers: { 
        "Authorization": "Basic ${authKey}", 
        "Content-type": "application/json; charset=UTF-8" 
    } 
}); 

Success response from SMS API
You will get the below response from SMS API calls 

{ 
 "result": 0, 
 "job_id":  "5e71f1b23630865c34443fb4" 
} 

where in job_id is further used in a separate api call to fetch the status of SMS delivery if required. 

Track the delivery status of an SMS sent with NodeJS 

You can track EnableX SMS Gateway jobs by providing their “job_id”. If Instant Delivery Notification Web Hook URL is configured, delivery notifications will be posted instantly. 

Request for Delivery Status of an SMS  

const axios = require('axios'); 
var Url = "https://api.enablex.io/sms/v1/messages/{job_id}"; 
Url = Url.replace("{job_id}", "5e71f1b23630865c34443fb4"); 

 const options = {   
  headers: {   
    "Authorization": "Basic ${authKey}",   
    "Content-Type": "application/json"   
  } 
}; 

 axios.get(URL, options 
    .then((res) => 
        console.log("RESPONSE ==== : ", res);  
    })  
    .catch((err) => {   
        console.log ("ERROR: ====", err); 
    }) 

Response in return of Delivery Status Request 

{ 
   "result": 0, 
 "job_id": "5e71f1b23630865c34443fb4", 

    "summary": { 
      "total": 10, 
      "sent": 10, 
      "delivered": 8, 
      "failed": 1, 
      "unknown": 1 
    }, 

    "detailed": [ 
      { 
        "to": "+99999999999", 
        "sent": "2020-10-16UTC08:29:42", 
        "delivered": "2020-10-1613:59:43", 
        "uuid": "1268999", 
        "status": "delivered" 
      } 
    ] 
  } 

How to handle SMS API errors in NodeJS 

In this example, we are using the axios library to make an HTTP POST request to the SMS API endpoint. The then block is used to handle a successful response, while the catch block is used to handle any errors that may occur, and it logs the error message based on logging library used in Nodejs project. 

axios.post(URL, data, options 
    .then((res) => 
        console.log("RESPONSE ==== : ", res);  
    })  

    .catch((err) => {   
        console.log ("ERROR: ====", err); 
    }) 

Other option would be to retrigger the SMS calls based on configured retries for your failures. E.g., you want to retry three times in case of SMS failure. In this example, we are logging the error to the console, but you could also send an email, SMS to the administrator, or display a user-friendly error message to the end user. 

Send SMS messages to multiple recipients using NodeJS 

Using EnableX SMS API, you can send SMS to a maximum of 50 recipients at a time. In case you are to send SMS to a group larger than 50 recipients, then you must loop API Call to send SMS in a batch of 50 recipients. 

const URL = "https://api.enablex.io/sms/v1/messages" 
const data = {  
    "from":"+44xxxxxxxx",   
    "body": "{$name} you are due to pay Rs. {$amount}",   
    "recipient": 
        {"to": "+91xxxxxx","name": "Kamal","amount": "30"}, 
        {"to": "+91yyyyyy","name": "Subrat","amount": "30"}, 
        {"to": "+91zzzzzz","name": "Kamal50","amount": "30"} 
     ], 

DLT Registration for Sending Bulk SMS in India 

Any business or organization based in India which has a valid business registration and wishes to send SMS to users in India can apply.  Individuals are not eligible to apply for DLT registration.   

If you meet these requirements, you can start the DLT registration process by filling out the application form and submitting it to TRAI. You may also need to pay a fee to complete the registration process. If you need help with the DLT registration process, you can Contact us. The EnableX team will help complete DLT registration, and you can then use EnableX’s powerful SMS API to send SMS anywhere in India! 

If you are looking for a way to add SMS messaging functionality to your Node.js application, EnableX is the perfect solution for you. With EnableX’s powerful API and easy-to-use interface, you can send SMS messages to any mobile phone number in the world with just a few lines of code. So why wait? Sign up today and get started sending SMS messages. 

Are you looking for feature-rich APIs to build exciting solutions?
Sign up for free to begin!
Signup Cpaas API