Sending SMS in JavaScript (Node.js): API Libraries and Practical Examples
In the modern world, SMS notifications remain one of the most reliable ways to communicate with users. Whether it's registration confirmation, a two-factor authentication code, or marketing campaigns — the ability to programmatically send SMS messages is critical for many web applications. In this article, we will look at how to implement sending SMS in JavaScript (Node.js) using various APIs and libraries.
Choosing an SMS Provider and Obtaining an API Key
The first step is to choose a service for sending SMS. There are many providers, such as Twilio, Nexmo (Vonage), Amazon SNS, ClickSend, and others. To get started, you will need:
- Register with the chosen service.
- Top up your balance or connect a test account.
- Obtain an API key, SID, and access token (each provider has its own terminology).
- Configure the sender (Sender ID) — a phone number or alphanumeric name.
Installing Required Libraries
To work with SMS provider APIs in Node.js, official SDKs are most often used. Let's look at installation using the popular service Twilio and the universal library axios for HTTP requests as examples.
# Installing the Twilio librarynpm install twilio
# Installing axios for REST API requestsnpm install axiosExample 1: Sending SMS via Twilio SDK
Twilio provides a convenient SDK for Node.js. After installation, create a file send-sms.js and add the following code:
const twilio = require('twilio');
// Your credentials from the Twilio consoleconst accountSid = process.env.TWILIO_ACCOUNT_SID;const authToken = process.env.TWILIO_AUTH_TOKEN;
const client = new twilio(accountSid, authToken);
async function sendSMS() { try { const message = await client.messages.create({ body: 'Hello! This is a test SMS from a Node.js application.', from: '+1234567890', // Number obtained from Twilio to: '+79001234567' // Recipient's number }); console.log('SMS sent. SID:', message.sid); } catch (error) { console.error('Error sending SMS:', error); }}
sendSMS();Important: Never store keys directly in the code. Use environment variables (.env file or system settings).
Example 2: Sending SMS via a Universal REST API
If your provider does not have an official SDK, you can use axios to send a POST request. Let's look at an example with an abstract SMS gateway:
const axios = require('axios');
const API_URL = 'https://api.sms-provider.com/v1/send';const API_KEY = process.env.SMS_API_KEY;
async function sendSMSViaREST(phone, message) { try { const response = await axios.post(API_URL, { apiKey: API_KEY, phone: phone, text: message, sender: 'MyApp' // Sender name }, { headers: { 'Content-Type': 'application/json' } }); console.log('Server response:', response.data); } catch (error) { console.error('Error:', error.response ? error.response.data : error.message); }}
// UsagesendSMSViaREST('+79001234567', 'Your confirmation code: 1234');Error Handling and Delivery Statuses
When working with SMS, it is important to consider possible errors:
- Invalid number — check the phone format (international format with +).
- Insufficient funds — monitor your account balance.
- Provider restrictions — some operators block mass mailings.
- Timeouts — use error handling and retry mechanisms.