How to Integrate SendAfrica SMS API with Node.js
A step-by-step tutorial on integrating the SendAfrica SMS API with Node.js, covering single messages, bulk SMS, and delivery webhooks.
How to Integrate SendAfrica SMS API with Node.js
Building an SMS-powered feature in your Node.js application is straightforward with the SendAfrica API. This tutorial walks you through setting up the integration from scratch, including sending single messages, bulk SMS, and handling delivery reports.
Prerequisites
- Node.js 18+ installed
- A SendAfrica account with API credentials
- Basic familiarity with REST APIs
Step 1: Install Dependencies
npm install axios dotenv
Step 2: Configure Environment Variables
Create a .env file in your project root:
SENDAFRICA_API_KEY=your_api_key_here
SENDAFRICA_BASE_URL=https://api.sendafrica.online/v1
Step 3: Create the SMS Client
// lib/sendafrica.js
require('dotenv').config();
const axios = require('axios');
const client = axios.create({
baseURL: process.env.SENDAFRICA_BASE_URL,
headers: {
'Authorization': `Bearer ${process.env.SENDAFRICA_API_KEY}`,
'Content-Type': 'application/json',
},
});
async function sendSMS(to, message) {
const response = await client.post('/sms/send', { to, message });
return response.data;
}
async function sendBulkSMS(recipients) {
const response = await client.post('/sms/bulk', { recipients });
return response.data;
}
module.exports = { sendSMS, sendBulkSMS };
Step 4: Send Your First SMS
// index.js
const { sendSMS } = require('./lib/sendafrica');
async function main() {
try {
const result = await sendSMS(
'+254712345678',
'Hello from SendAfrica! Your verification code is 4829.'
);
console.log('SMS sent:', result);
} catch (error) {
console.error('Failed to send SMS:', error.response?.data || error.message);
}
}
main();
Step 5: Handle Delivery Reports
SendAfrica supports webhooks for delivery reports. Set up an endpoint in your Express app:
app.post('/webhooks/sms-delivery', (req, res) => {
const { message_id, status, delivered_at } = req.body;
console.log(`Message ${message_id}: ${status}`);
// Update your database with delivery status
res.sendStatus(200);
});
Error Handling
The API returns standard HTTP status codes:
- 200: Message sent successfully
- 400: Invalid request (check phone format)
- 401: Invalid API key
- 429: Rate limit exceeded
- 500: Server error (retry with exponential backoff)
Best Practices
- Validate phone numbers before sending
- Implement retry logic with exponential backoff
- Cache delivery reports to avoid duplicate processing
- Rate limit your outgoing messages to stay within API limits
- Log everything for debugging and audit purposes
Full Example
Check out the complete integration example on our GitHub repository with production-ready error handling, retry logic, and TypeScript support.
Ready to build? Sign up for SendAfrica and start sending SMS in minutes.
Comments (0)
No comments yet. Be the first to share your thoughts!