Developer Guide
Node.js SMS Gateway Integration
NPM package with async/await, TypeScript types, Express middleware, and webhook handlers — ship SMS features in minutes.
🟢
npm install
One command installs the SDK, TypeScript definitions, and all dependencies.
⚡
Async / Await
Promise-based API that works naturally with modern JavaScript and TypeScript.
🔄
Webhook Ready
Built-in Express middleware for validating and processing delivery webhooks.
Before You Begin
Prerequisites
System Requirements
- Node.js 16.x or higher (18 LTS recommended)
- npm or yarn package manager
- An HTTPS-capable server (for webhooks)
Account Setup
- Sign up at onlinesmsservice.com
- Get API Key from Dashboard → Settings
- Register DLT templates (required in India)
Quick Start
Install & Send Your First SMS
Terminal
npm install onlinesmsservice --save
JavaScript — send-sms.js
const { SMSClient } = require('onlinesmsservice');
const client = new SMSClient(process.env.SMS_API_KEY);
// Send a single SMS
async function sendOTP(phone, otp) {
try {
const result = await client.send({
to: phone,
message: `Your OTP is ${otp}. Valid for 5 minutes.`,
sender: 'YOURID',
type: 'transactional'
});
console.log('Message ID:', result.messageId);
console.log('Status:', result.status); // "queued"
console.log('Credits:', result.creditsUsed);
return result;
} catch (error) {
console.error('SMS failed:', error.message);
throw error;
}
}
sendOTP('919876543210', '482910');
Bulk Sending
Send Bulk SMS (up to 10,000 per call)
JavaScript — bulk-send.js
const { SMSClient } = require('onlinesmsservice');
const client = new SMSClient(process.env.SMS_API_KEY);
async function sendCampaign(phones, message) {
const result = await client.sendBulk({
to: phones, // Array of phone numbers
message,
sender: 'YOURID',
type: 'promotional'
});
console.log(`Sent: ${result.successCount}/${result.totalCount}`);
// Check individual statuses
result.results.forEach(r => {
if (r.status === 'failed') {
console.warn(`Failed: ${r.phone} — ${r.error}`);
}
});
return result;
}
const phones = ['919876543210', '919876543211', '919876543212'];
sendCampaign(phones, 'Flash sale! 40% off everything today only.');
Express.js
Express.js Integration
Add SMS capabilities to your Express app with built-in middleware for sending and receiving webhooks.
JavaScript — server.js
const express = require('express');
const { SMSClient, webhookMiddleware } = require('onlinesmsservice');
const app = express();
const sms = new SMSClient(process.env.SMS_API_KEY);
app.use(express.json());
// Send SMS endpoint
app.post('/api/send-otp', async (req, res) => {
const { phone } = req.body;
const otp = Math.floor(100000 + Math.random() * 900000);
try {
const result = await sms.send({
to: phone,
message: `Your verification code is ${otp}`,
type: 'transactional'
});
// Store OTP in your database/cache
res.json({ success: true, messageId: result.messageId });
} catch (err) {
res.status(500).json({ success: false, error: err.message });
}
});
// Delivery webhook endpoint
app.post('/webhooks/sms',
webhookMiddleware(process.env.SMS_WEBHOOK_SECRET),
(req, res) => {
const { messageId, status, deliveredAt } = req.body;
console.log(`Message ${messageId}: ${status} at ${deliveredAt}`);
// Update your database with delivery status
res.sendStatus(200);
}
);
app.listen(3000, () => console.log('Server running on port 3000'));
TypeScript
TypeScript Support
Full type definitions included — get autocomplete and compile-time safety out of the box.
TypeScript — sms-service.ts
import { SMSClient, SendResult, MessageOptions } from 'onlinesmsservice';
const client = new SMSClient(process.env.SMS_API_KEY!);
interface OTPPayload {
phone: string;
otp: string;
expiresInMinutes?: number;
}
async function sendOTP({ phone, otp, expiresInMinutes = 5 }: OTPPayload): Promise<SendResult> {
const options: MessageOptions = {
to: phone,
message: `Your OTP is ${otp}. Valid for ${expiresInMinutes} min.`,
sender: 'YOURID',
type: 'transactional',
};
return client.send(options);
}
export { sendOTP };
Reference
Error Handling & Response Codes
| HTTP Code | Error Class | Action |
|---|---|---|
200 | — | Message queued successfully |
400 | ValidationError | Fix request parameters |
401 | AuthError | Check API key |
402 | BalanceError | Top up account |
429 | RateLimitError | SDK auto-retries with backoff |
500 | ServerError | SDK auto-retries (3 attempts) |
Best Practices
Production Checklist
🔐 Security
- Store API key in
process.env, never in code - Use webhook signature validation middleware
- Whitelist server IPs in your dashboard
⚡ Performance
- Use bulk endpoint for 100+ messages
- Queue SMS jobs with BullMQ or similar
- Enable keep-alive connections (SDK default)
Start Sending SMS from Node.js
Get 500 free SMS credits upon successful registration and DLT mapping with an approved telemarketer. npm install and start sending in minutes.