APIs · Beginner · 26 min
Send SMS from your app with the Africa's Talking API
By Padding · Updated 18 Nov 2026
Node.js 26.13 LTS · Express 5.3 · africastalking 0.8 · node:26 image (Debian)
You will build a Node.js 26 app that sends one-time sign-in codes by SMS through the Africa's Talking API, formats numbers in E.164, reads the per-recipient status and cost, and records delivery reports.
On this page
Africa's Talking is an API platform for SMS, USSD, voice and airtime across many African countries. Its SMS API takes one HTTP request with your username, a list of phone numbers and the message, and answers with a status for each number. A few seconds later, it can post a delivery report to a URL you choose, saying whether each handset actually received the message.
In this tutorial you build the thing most apps need SMS for first: one-time sign-in codes. Your app formats the number, sends the code, checks what Africa's Talking said about that recipient, knows what the message cost, and records the delivery report when it arrives.
You start against a small practice gateway that runs on your computer and copies the request and response shapes of the real API, so you can trigger refused numbers, failed deliveries and wrong API keys on purpose without an account. Later steps switch the same code to the Africa's Talking sandbox and its online phone simulator, and show the official Node SDK as an alternative to writing the request yourself.
SMS is a good fit for codes in markets where many people use low-cost Android phones or feature phones on prepaid data: the message arrives over the mobile network, with no app and no data bundle needed.
Step 1 · Create the project and its settings
Make a folder, install Express 5.3 and mark the project as using ES modules:
mkdir -p ~/at-sms-demo
cd ~/at-sms-demo
npm init -y > /dev/null
npm pkg set type=module
npm install express@5.3.0Now create .env, the file that holds the settings. umask 077 makes it readable only by you from the moment it exists. For now it points at the practice gateway on port 4010 with a practice API key that works nowhere else. The sandbox's username is always sandbox, so that value stays when you switch:
cd ~/at-sms-demo
(
umask 077
cat > .env <<'EOF'
AT_USERNAME=sandbox
AT_API_KEY=practice-api-key
AT_SMS_URL=http://127.0.0.1:4010/version1/messaging
AT_SENDER_ID=
DEFAULT_COUNTRY=KE
PUBLIC_BASE_URL=http://127.0.0.1:3000
EOF
printf 'REPORT_TOKEN=%s\n' "$(node -e 'console.log(require("node:crypto").randomBytes(24).toString("base64url"))')" >> .env
)
ls -l .envAT_SENDER_IDstays empty in the sandbox. On a live account it holds a sender ID or short code registered to you.DEFAULT_COUNTRYis the country assumed when someone types a local number such as0712 345 678.REPORT_TOKENis a random value that becomes part of your delivery report URL, so strangers cannot post fake reports to it. It is generated, never typed.
If the project is in Git, add .env to .gitignore before your first commit: see keep secrets out of Git.
Check it worked
cd ~/at-sms-demo
node -p "require('express/package.json').version"
grep -c '=' .envThe listing above starts with -rw-------, the version is 5.3.0, and .env has 7 settings.
Step 2 · Run a practice SMS gateway
This server plays Africa's Talking. It accepts the same form-encoded request on /version1/messaging, checks the apiKey header, answers with the documented SMSMessageData shape, and a second later posts a delivery report to your app. It also keeps an outbox, which stands in for the phone simulator you use later:
- a number that is not in E.164 form is refused with status code
403(InvalidPhoneNumber) +254711000000is accepted, but its delivery report saysFailedwith the reasonUserDoesNotExist- every other number is accepted and delivered
cd ~/at-sms-demo
cat > practice-gateway.js <<'JS'
// A practice stand-in for the Africa's Talking SMS API. It copies the documented
// request and response shapes. It is not Africa's Talking's code.
import crypto from 'node:crypto';
import http from 'node:http';
const { AT_USERNAME, AT_API_KEY, PUBLIC_BASE_URL, REPORT_TOKEN } = process.env;
const PRICE_PER_PART = 0.8; // KES, the figure in the official SDK's sample response
const outbox = [];
// How many SMS parts a message needs: GSM-7 160/153, otherwise UCS-2 70/67.
const GSM = '@£$¥èéùìòÇ\nØø\rÅåΔ_ΦΓΛΩΠΨΣΘΞÆæßÉ !"#¤%&\'()*+,-./0123456789:;<=>?¡ABCDEFGHIJKLMNOPQRSTUVWXYZÄÖÑܧ¿abcdefghijklmnopqrstuvwxyzäöñüà';
const GSM_EXT = '^{}\\[~]|€\f';
function parts(text) {
const chars = [...text];
if (chars.every((c) => GSM.includes(c) || GSM_EXT.includes(c))) {
const n = chars.reduce((sum, c) => sum + (GSM_EXT.includes(c) ? 2 : 1), 0);
return n <= 160 ? 1 : Math.ceil(n / 153);
}
return text.length <= 70 ? 1 : Math.ceil(text.length / 67);
}
const money = (n) => `KES ${n.toFixed(4)}`;
function reply(res, status, body) {
const json = typeof body !== 'string';
res.writeHead(status, { 'Content-Type': json ? 'application/json' : 'text/plain' });
res.end(json ? JSON.stringify(body) : body);
}
async function readForm(req) {
let raw = '';
for await (const chunk of req) raw += chunk;
return new URLSearchParams(raw);
}
async function deliveryReport(recipient) {
const failed = recipient.number === '+254711000000';
const form = new URLSearchParams({
id: recipient.messageId,
status: failed ? 'Failed' : 'Success',
phoneNumber: recipient.number,
networkCode: recipient.number.startsWith('+254') ? '63902' : '62130',
retryCount: '0',
});
if (failed) form.set('failureReason', 'UserDoesNotExist');
try {
await fetch(`${PUBLIC_BASE_URL}/sms/delivery-reports/${REPORT_TOKEN}`, {
method: 'POST', body: form, signal: AbortSignal.timeout(5000),
});
console.log(`report sent for ${recipient.messageId}`);
} catch (err) {
console.log(`report for ${recipient.messageId} not delivered: ${err.cause?.code ?? err.message}`);
}
}
http.createServer(async (req, res) => {
const url = new URL(req.url, 'http://localhost');
if (req.method === 'GET' && url.pathname === '/practice/outbox') {
return reply(res, 200, outbox.slice(-3).reverse());
}
if (req.method !== 'POST' || url.pathname !== '/version1/messaging') {
return reply(res, 404, 'Not found');
}
const form = await readForm(req);
if (req.headers.apikey !== AT_API_KEY || form.get('username') !== AT_USERNAME) {
return reply(res, 401, 'The supplied authentication is invalid');
}
const message = form.get('message') ?? '';
const to = (form.get('to') ?? '').split(',').map((s) => s.trim()).filter(Boolean);
if (!message || to.length === 0) return reply(res, 400, 'Missing to or message');
const n = parts(message);
const recipients = to.map((number) => {
if (!/^\+[1-9]\d{9,14}$/.test(number)) {
return { statusCode: 403, number, status: 'InvalidPhoneNumber', cost: '0', messageId: 'None' };
}
outbox.push({ to: number, from: form.get('from') || 'sandbox default', message });
const messageId = `ATXid_${crypto.randomBytes(16).toString('hex')}`;
return { statusCode: 101, number, status: 'Success', cost: money(PRICE_PER_PART * n), messageId };
});
const sent = recipients.filter((r) => r.statusCode === 101);
reply(res, 201, { SMSMessageData: {
Message: `Sent to ${sent.length}/${to.length} Total Cost: ${money(sent.length * n * PRICE_PER_PART)}`,
Recipients: recipients,
} });
for (const r of sent) setTimeout(() => deliveryReport(r), 1000);
}).listen(4010, '127.0.0.1', () => console.log('practice SMS gateway on http://127.0.0.1:4010'));
JS63902 and 62130 in the reports are network codes, a country code plus an operator code: Safaricom in Kenya and MTN in Nigeria.
Start the gateway in a second terminal and leave it running:
cd ~/at-sms-demo
node --env-file=.env practice-gateway.jsCheck it worked
The second terminal prints practice SMS gateway on http://127.0.0.1:4010. In your first terminal, send a request without an API key:
curl -s -X POST http://127.0.0.1:4010/version1/messaging -d 'username=sandbox&to=%2B254712345678&message=hi'
echoThe answer is The supplied authentication is invalid, with HTTP status 401.
Step 3 · Format phone numbers in E.164
Africa's Talking wants every number in international form: a +, the country calling code, then the national number without its leading 0. That format is E.164, and it allows at most 15 digits. People type numbers every other way, with spaces, dashes, a leading 0 or 00, so convert once, where the number enters your app, and refuse anything that does not fit.
Create phone.js:
cd ~/at-sms-demo
cat > phone.js <<'JS'
const CALLING_CODES = { KE: '254', NG: '234', GH: '233', UG: '256', TZ: '255', RW: '250', ZA: '27' };
// Turns a number as people type it into E.164 (+, country code, number), or null.
// This checks the shape only. It cannot tell whether the number exists.
export function toE164(input, defaultCountry = 'KE') {
let s = String(input ?? '').replace(/[\s().-]/g, '');
if (s.startsWith('00')) {
s = `+${s.slice(2)}`;
} else if (!s.startsWith('+')) {
const code = CALLING_CODES[defaultCountry];
if (!code) throw new Error(`no calling code for ${defaultCountry}`);
s = s.startsWith(code) && s.length >= code.length + 9 ? `+${s}` : `+${code}${s.replace(/^0/, '')}`;
}
return /^\+[1-9]\d{9,14}$/.test(s) ? s : null;
}
JSA number that already starts with + or 00 keeps its own country, so a Ghanaian number typed into a Kenyan app is not rewritten. The country table is deliberately short: add the countries you serve. For full validation per country and operator, the libphonenumber-js package holds the numbering plans, and the official Africa's Talking SDK uses Google's libphonenumber for the same job.
Check it worked
cd ~/at-sms-demo
cat > check-phone.js <<'JS'
import { toE164 } from './phone.js';
const samples = [
['0712 345 678', 'KE'],
['254712345678', 'KE'],
['0110-123-456', 'KE'],
['0803 123 4567', 'NG'],
['+233 24 123 4567', 'NG'],
['00256 772 123456', 'KE'],
['12345', 'KE'],
['call me', 'KE'],
];
for (const [input, country] of samples) console.log(input.padEnd(18), country, '->', toE164(input, country));
JS
node check-phone.jsThe output is:
0712 345 678 KE -> +254712345678
254712345678 KE -> +254712345678
0110-123-456 KE -> +254110123456
0803 123 4567 NG -> +2348031234567
+233 24 123 4567 NG -> +233241234567
00256 772 123456 KE -> +256772123456
12345 KE -> null
call me KE -> nullStep 4 · Send an SMS with fetch
The SMS API is one POST with a form-encoded body, not JSON. Your API key goes in an apiKey header, never in the URL or the body. to takes one number or several joined by commas. On success the API answers 201 Created, and the body lists every recipient with its own statusCode. A 201 only means the request was understood: one number in it can still be refused.
Create sms.js:
cd ~/at-sms-demo
cat > sms.js <<'JS'
function setting(name) {
const value = process.env[name];
if (!value) throw new Error(`${name} is not set`);
return value;
}
// Africa's Talking answered, but not with 201: a bad key, a bad request or an outage.
export class SmsError extends Error {
constructor(message, httpStatus) {
super(message);
this.httpStatus = httpStatus;
}
}
// 100 Processed, 101 Success, 102 Queued. Anything else means that number was refused.
const ACCEPTED = new Set([100, 101, 102]);
export async function sendSms({ to, message, from = process.env.AT_SENDER_ID }) {
const form = new URLSearchParams({
username: setting('AT_USERNAME'),
to: [].concat(to).join(','),
message,
bulkSMSMode: '1',
});
if (from) form.set('from', from);
const res = await fetch(setting('AT_SMS_URL'), {
method: 'POST',
headers: { apiKey: setting('AT_API_KEY'), Accept: 'application/json' },
body: form, // fetch sets Content-Type: application/x-www-form-urlencoded
signal: AbortSignal.timeout(10_000),
});
const text = await res.text();
if (res.status !== 201) {
throw new SmsError(`Africa's Talking answered ${res.status}: ${text.slice(0, 200)}`, res.status);
}
const data = JSON.parse(text).SMSMessageData;
return {
summary: data.Message,
recipients: data.Recipients.map((r) => ({
number: r.number,
statusCode: r.statusCode,
status: r.status,
cost: r.cost,
messageId: r.messageId,
accepted: ACCEPTED.has(r.statusCode),
})),
};
}
JSDecide on the numeric statusCode, not the status text: codes are the stable part of the contract. Codes you will meet early are 403 InvalidPhoneNumber, 405 InsufficientBalance (your account has run out of credit), 406 UserInBlacklist (the person has blocked messages from you) and 402 InvalidSenderId (on a live account, a sender ID that is not registered to you). Keep the messageId of every accepted message: the delivery report refers to it.
Check it worked
Send one message to two valid numbers and a number with digits missing:
cd ~/at-sms-demo
cat > send-one.js <<'JS'
import { sendSms } from './sms.js';
const result = await sendSms({
to: ['+254712345678', '+2348031234567', '+2547123'],
message: 'Hello from the SMS demo',
});
console.log(result.summary);
for (const r of result.recipients) {
console.log(r.accepted ? 'OK ' : 'FAIL', r.number, r.statusCode, r.status, r.cost);
}
JS
node --env-file=.env send-one.jsThe output is:
Sent to 2/3 Total Cost: KES 1.6000
OK +254712345678 101 Success KES 0.8000
OK +2348031234567 101 Success KES 0.8000
FAIL +2547123 403 InvalidPhoneNumber 0The gateway terminal also prints two lines starting report for ATXid_ and ending not delivered: ECONNREFUSED. Your app is not running yet, so nothing receives the delivery reports. That changes in a later step.
Step 5 · Handle failures and count the cost
A send can go wrong in three different ways, and each needs a different response:
- Africa's Talking refuses the request, with a status other than
201: a wrong API key or username gives401.sendSmsthrowsSmsError. Retrying will not help. Fix the settings. - No answer arrives: a timeout or a network error. The message may or may not have gone out. For a sign-in code, do not resend automatically, or a slow network becomes two codes and two charges. Let the person ask again after a short wait.
- The request succeeds, but a recipient is refused: check
acceptedfor each number, as in the previous step.
Write a script that triggers the first two on purpose, after one good send:
cd ~/at-sms-demo
cat > failures.js <<'JS'
import { sendSms, SmsError } from './sms.js';
async function attempt(label) {
try {
const { recipients: [r] } = await sendSms({ to: '+254712345678', message: 'Checking the connection' });
console.log(label, 'sent,', r.statusCode);
} catch (err) {
if (err instanceof SmsError) console.log(label, 'refused,', err.httpStatus);
else if (err.name === 'TimeoutError') console.log(label, 'timed out, outcome unknown');
else console.log(label, 'network problem,', err.cause?.code ?? err.message);
}
}
await attempt('good key:');
const realKey = process.env.AT_API_KEY;
process.env.AT_API_KEY = 'wrong-key';
await attempt('wrong key:');
process.env.AT_API_KEY = realKey;
process.env.AT_SMS_URL = 'http://127.0.0.1:4019/version1/messaging';
await attempt('nothing listening:');
JS
node --env-file=.env failures.jsNothing in this tutorial listens on port 4019, so the last call cannot connect.
The cost is the other thing to watch. An SMS carries 160 characters when every character is in the GSM-7 alphabet, the basic Latin set that phones have always supported. One character outside it, such as an emoji, a curly quote pasted from a word processor or a Yorùbá ẹ, switches the whole message to UCS-2, which fits only 70. Longer messages are split into parts of 153 or 67 characters, and each part is charged as one SMS. For codes, keep the text short and plain. For messages in your users' own languages, accept the higher cost and count it.
Create sms-parts.js, which works out the encoding and the number of parts before you send:
cd ~/at-sms-demo
cat > sms-parts.js <<'JS'
// GSM 03.38 basic character set and the extension characters that take two places.
const GSM = '@£$¥èéùìòÇ\nØø\rÅåΔ_ΦΓΛΩΠΨΣΘΞÆæßÉ !"#¤%&\'()*+,-./0123456789:;<=>?¡ABCDEFGHIJKLMNOPQRSTUVWXYZÄÖÑܧ¿abcdefghijklmnopqrstuvwxyzäöñüà';
const GSM_EXT = '^{}\\[~]|€\f';
export function smsParts(text) {
const chars = [...text];
if (chars.every((c) => GSM.includes(c) || GSM_EXT.includes(c))) {
const length = chars.reduce((n, c) => n + (GSM_EXT.includes(c) ? 2 : 1), 0);
return { encoding: 'GSM-7', length, parts: length <= 160 ? 1 : Math.ceil(length / 153) };
}
// UCS-2: 70 code units in one SMS, 67 per part once it is split.
const length = text.length;
return { encoding: 'UCS-2', length, parts: length <= 70 ? 1 : Math.ceil(length / 67) };
}
JS
cat > cost.js <<'JS'
import { smsParts } from './sms-parts.js';
import { sendSms } from './sms.js';
const code = 'Your sign-in code is 482913. It expires in 5 minutes. Do not share it.';
const texts = { plain: code, emoji: `${code} 🙂`, yoruba: `Ẹ kú àárọ̀. ${code}` };
for (const [name, text] of Object.entries(texts)) {
const { encoding, length, parts } = smsParts(text);
const { recipients: [r] } = await sendSms({ to: '+254712345678', message: text });
console.log(name.padEnd(6), encoding, length, `${parts} part(s)`, r.cost);
}
JS
node --env-file=.env cost.jsCheck it worked
failures.js prints:
good key: sent, 101
wrong key: refused, 401
nothing listening: network problem, ECONNREFUSEDcost.js prints:
plain GSM-7 70 1 part(s) KES 0.8000
emoji UCS-2 73 2 part(s) KES 1.6000
yoruba UCS-2 82 2 part(s) KES 1.6000The same code costs twice as much with a smiley at the end. Real prices depend on the country and the operator, and the cost field tells you what each message was charged. Log it next to the messageId so you can reconcile your spending later.
Step 6 · Send sign-in codes and record delivery reports
Now put the pieces into an app. It has three routes:
POST /otptakes a phone number, creates a six-digit code, and sends it. It allows one code per number per minute.POST /otp/verifychecks a code. A code works once, for five minutes, with at most five tries.POST /sms/delivery-reports/<token>receives Africa's Talking's delivery reports. They arrive form-encoded, with the fieldsid(themessageId),status,phoneNumber,networkCode,failureReasonfor failed messages, andretryCount. The report has no signature field, so the random token in the path is what keeps strangers out.
Codes are kept as hashes, compared in constant time, and never written to a log. Create otp.js for the code rules:
cd ~/at-sms-demo
cat > otp.js <<'JS'
import crypto from 'node:crypto';
const TTL_MS = 5 * 60_000;
const RESEND_MS = 60_000;
const MAX_TRIES = 5;
const codes = new Map(); // phone -> { hash, expiresAt, sentAt, tries }. Use a database in production.
const hash = (code) => crypto.createHash('sha256').update(code).digest();
export function issueCode(phone, now = Date.now()) {
const current = codes.get(phone);
if (current && now - current.sentAt < RESEND_MS) {
return { retryAfter: Math.ceil((RESEND_MS - (now - current.sentAt)) / 1000) };
}
const code = String(crypto.randomInt(0, 1_000_000)).padStart(6, '0');
codes.set(phone, { hash: hash(code), expiresAt: now + TTL_MS, sentAt: now, tries: 0 });
return { code };
}
export function checkCode(phone, code, now = Date.now()) {
const entry = codes.get(phone);
if (!entry || now > entry.expiresAt) return 'expired';
if (entry.tries >= MAX_TRIES) return 'locked';
entry.tries += 1;
if (!crypto.timingSafeEqual(hash(String(code)), entry.hash)) return 'wrong';
codes.delete(phone);
return 'ok';
}
export function forgetCode(phone) {
codes.delete(phone);
}
JSThen server.js for the routes:
cd ~/at-sms-demo
cat > server.js <<'JS'
import express from 'express';
import { checkCode, forgetCode, issueCode } from './otp.js';
import { toE164 } from './phone.js';
import { sendSms, SmsError } from './sms.js';
const { REPORT_TOKEN, DEFAULT_COUNTRY = 'KE' } = process.env;
if (!REPORT_TOKEN) throw new Error('REPORT_TOKEN is not set');
const app = express();
app.use(express.json());
const deliveries = new Map(); // messageId -> { status, failureReason }. Use a database in production.
app.post('/otp', async (req, res) => {
const phone = toE164(req.body?.phone, DEFAULT_COUNTRY);
if (!phone) return res.status(400).json({ error: 'Enter your full mobile number' });
const issued = issueCode(phone);
if (issued.retryAfter) {
return res.status(429).set('Retry-After', String(issued.retryAfter))
.json({ error: 'Wait a minute before asking for another code' });
}
try {
const { recipients: [r] } = await sendSms({
to: phone,
message: `Your sign-in code is ${issued.code}. It expires in 5 minutes. Do not share it.`,
});
if (!r?.accepted) {
forgetCode(phone);
console.log(`code refused: ${r?.statusCode} ${r?.status}`);
return res.status(422).json({ error: 'We cannot send a code to that number' });
}
deliveries.set(r.messageId, { status: r.status, failureReason: null });
console.log(`code sent: ${r.messageId} ${r.cost}`);
res.status(202).json({ messageId: r.messageId });
} catch (err) {
// A refusal means no SMS went out. After a timeout one may still arrive, so keep the code.
if (err instanceof SmsError) forgetCode(phone);
console.log(`code not sent: ${err.message}`);
res.status(503).json({ error: 'SMS is unavailable. If a code arrives, you can still use it.' });
}
});
app.post('/otp/verify', (req, res) => {
const phone = toE164(req.body?.phone, DEFAULT_COUNTRY);
const result = phone ? checkCode(phone, String(req.body?.code ?? '')) : 'expired';
if (result === 'ok') return res.json({ verified: true });
res.status(result === 'locked' ? 429 : 400).json({ verified: false, reason: result });
});
app.post(`/sms/delivery-reports/${REPORT_TOKEN}`, express.urlencoded({ extended: false }), (req, res) => {
const { id, status, failureReason } = req.body ?? {};
const entry = deliveries.get(id);
if (entry) Object.assign(entry, { status, failureReason: failureReason ?? null });
console.log(`delivery report ${id}: ${status}${failureReason ? ` (${failureReason})` : ''}`);
res.sendStatus(200);
});
app.listen(3000, '127.0.0.1', (err) => {
if (err) throw err;
console.log('OTP app on http://127.0.0.1:3000');
});
JSThe delivery report route answers 200 straight away and does nothing slow. Africa's Talking only needs to know the report arrived. In a larger app you would store it and do any follow-up work, such as offering a voice call when a code fails, outside the request.
Start the app in a third terminal and leave it running:
cd ~/at-sms-demo
node --env-file=.env server.jsCheck it worked
Ask for a code, ask again at once, then look at the practice outbox, which shows the newest messages first:
curl -s -X POST http://127.0.0.1:3000/otp -H 'Content-Type: application/json' -d '{"phone":"0712 345 678"}'
echo
curl -s -X POST http://127.0.0.1:3000/otp -H 'Content-Type: application/json' -d '{"phone":"0712 345 678"}'
echo
curl -s http://127.0.0.1:4010/practice/outbox
echoThe first call answers {"messageId":"ATXid_..."}. The second answers {"error":"Wait a minute before asking for another code"}, because the minute is not up. The first outbox entry is to +254712345678 with the text Your sign-in code is followed by six digits. Within a second or two, the app's terminal prints delivery report ATXid_...: Success.
Try a wrong code:
curl -s -X POST http://127.0.0.1:3000/otp/verify -H 'Content-Type: application/json' -d '{"phone":"+254712345678","code":"000000"}'
echoIt answers {"verified":false,"reason":"wrong"}. Now send the code from the outbox. Replace 123456 with the six digits you saw:
curl -s -X POST http://127.0.0.1:3000/otp/verify -H 'Content-Type: application/json' -d '{"phone":"+254712345678","code":"123456"}'It answers {"verified":true}. Send it a second time and the answer is {"verified":false,"reason":"expired"}, because a code works once.
Last, ask for a code for a number that the practice gateway accepts but cannot deliver to:
curl -s -X POST http://127.0.0.1:3000/otp -H 'Content-Type: application/json' -d '{"phone":"0711 000 000"}'
echoIt still answers with a messageId, because Africa's Talking accepted the message. A second later the app's terminal prints delivery report ATXid_...: Failed (UserDoesNotExist). Only the delivery report tells you the code never reached a phone.
Step 7 · Switch to the Africa's Talking sandbox
When the flow works locally, point the same code at the real sandbox. Sandbox messages go to an online phone simulator, not to real phones, and cost nothing.
- Sign up or log in at account.africastalking.com. Every account has a sandbox app, whose username is
sandbox. - In the sandbox app's settings, generate an API key and copy it.
- Open the simulator at simulator.africastalking.com, enter a phone number in E.164 form, such as
+254712345678, and launch it. Messages sent to that number appear on the simulated phone.
Stop the practice gateway with Ctrl+C. Open .env in a text editor and change these two lines, pasting your key in place of the placeholder. Editing the file keeps the key out of your shell history:
AT_API_KEY=<your sandbox API key>
AT_SMS_URL=https://api.sandbox.africastalking.com/version1/messagingRestart the app with Ctrl+C and node --env-file=.env server.js, then ask for a code for the number in the simulator:
curl -s -X POST http://127.0.0.1:3000/otp -H 'Content-Type: application/json' -d '{"phone":"+254712345678"}'Delivery reports need a public HTTPS address, because Africa's Talking's servers cannot reach 127.0.0.1. Once the app runs behind HTTPS on a server, set PUBLIC_BASE_URL to that address, and in the dashboard's SMS callback settings enter your delivery reports URL: your address, then /sms/delivery-reports/, then the REPORT_TOKEN value from .env.
Before going live, create a live app, top up its balance, use its own username and API key, set AT_SMS_URL to https://api.africastalking.com/version1/messaging (check the SMS docs for the current address), and apply for a sender ID in the dashboard so messages show your name. Do not reuse the sandbox key anywhere else.
Check it worked
The simulated phone shows Your sign-in code is and six digits, and curl printed a messageId starting ATXid_. Send those six digits to /otp/verify as in the previous step and the answer is {"verified":true}. If curl prints SMS is unavailable and the app logs answered 401, the API key or username in .env is wrong.
Step 8 · Send with the official Node SDK
Africa's Talking publishes an SDK for Node.js, africastalking on npm. It builds the same form request, validates numbers with libphonenumber before it sends, and returns the same SMSMessageData body. Use it if you also need its other services, such as airtime or USSD. The fetch version has no dependencies and lets you set your own timeout.
cd ~/at-sms-demo
npm install africastalking@0.8.4
cat > sdk-send.js <<'JS'
import AfricasTalking from 'africastalking';
import { toE164 } from './phone.js';
const at = AfricasTalking({ username: process.env.AT_USERNAME, apiKey: process.env.AT_API_KEY });
const to = toE164(process.argv[2], process.env.DEFAULT_COUNTRY ?? 'KE');
if (!to) throw new Error('Pass a phone number, for example: node --env-file=.env sdk-send.js 0712345678');
try {
const result = await at.SMS.send({ to: [to], message: "Hello from the Africa's Talking Node SDK" });
for (const r of result.SMSMessageData.Recipients) console.log(r.number, r.statusCode, r.status, r.cost);
} catch (err) {
console.error('send failed:', err.response?.status ?? '', err.message);
process.exitCode = 1;
}
JSThe SDK chooses the host itself: with the username sandbox it calls api.sandbox.africastalking.com, and with any other username the live API. AT_SMS_URL has no effect on it. Run it with your sandbox key in .env and the simulator open:
cd ~/at-sms-demo
node --env-file=.env sdk-send.js 0712345678Check it worked
The output is one line like +254712345678 101 Success KES 0.0000, with the sandbox's own cost figure, and the message appears on the simulated phone.
Step 9 · Clean up
Stop the app and, if it is still running, the practice gateway with Ctrl+C in their terminals. Then delete the folder, which holds your API key:
cd ~
rm -rf ~/at-sms-demoCheck it worked
ls ~/at-sms-demo reports that the folder does not exist. If you created a sandbox API key only for this tutorial, generate a new one in the dashboard so the copied key stops working.
Next steps
- Handle slow and failing providers in one place: call third-party APIs reliably with timeouts, retries and a circuit breaker.
- See callbacks from the sending side, with signatures and retries: send webhooks with signatures and retries.
- Check signed callbacks from providers that do sign them: verify webhook signatures in Node.js.
- Text customers a receipt after they pay by M-Pesa: collect M-Pesa payments with the Daraja STK Push API.
Related tutorials
- Send webhooks with signatures, retries and backoffYou will build a Node.js 26 webhook sender that signs each delivery the Standard Webhooks way, keeps a queue and an attempt log in SQLite, retries failures with exponential backoff and jitter, gives up after a limit, and replays a delivery on request.
- Call third-party APIs reliably with timeouts, retries and a circuit breakerYou will build a reusable Node.js 26 API client that gives every request a deadline, retries only what is safe with backoff and jitter, honours Retry-After, stops calling a dead service with a circuit breaker and logs each attempt without leaking the API key.
- How to Receive and Verify Webhooks Safely in Node.jsYou will build an Express 5.3 webhook receiver on Node.js 26 that checks an HMAC-SHA256 signature over the raw request body, compares it in constant time, rejects stale timestamps and duplicate events, and a small sender that proves each rejection works.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials