Skip to content
Connect Media Connect Media

How to Send SMS with Node.js

Node.js 18 and later include fetch, so you can send SMS without any extra packages. This tutorial uses the Connect Media API.

Node.js

1. Set your API key

Create a key under Profile → API keys in the dashboard and set it as CM_API_KEY.

2. A reusable sendSms helper

// Node.js 18+ (built-in fetch)
const API_URL = 'https://dashboard.connectmedia.co.ke/api.php';

async function sendSms(to, message, sender) {
  const res = await fetch(API_URL, {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${process.env.CM_API_KEY}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ action: 'send', to, message, ...(sender && { sender }) }),
    signal: AbortSignal.timeout(15000),
  });
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  return res.json();
}

const result = await sendSms('254712345678', 'Your code is 4821. It expires in 5 minutes.');
if (result.code !== '201') console.error('Not accepted:', result.message);

3. Use it in an Express route

import express from 'express';

const app = express();
app.use(express.json());

app.post('/orders/:id/shipped', async (req, res) => {
  const { phone, orderId } = req.body;
  // Respond fast; send the SMS without blocking the request.
  res.status(202).json({ ok: true });
  sendSms(phone, `Order #${orderId} has shipped.`).catch(console.error);
});

app.listen(3000);

Tips

  • Never call the API from the browser. Your key would be exposed; always send from your server.
  • OTPs: generate the code server-side, store a hash with an expiry, and send it by SMS. See SMS OTP.
  • Retries: a retry after a timeout can duplicate a message; de-duplicate on your side.

Other languages: PHP · Python. Full reference: API docs.

Get started

Create a Connect Media account — SMS from KES 1.0, no minimum top-up, credit that never expires, and one account for Safaricom, Airtel and Telkom. Call +254 707 339 945 or email info@connectmedia.co.ke.

Frequently asked questions

How do I send SMS from Node.js?

Use fetch to POST JSON with action send, the number and the message to the Connect Media API, with your API key as a Bearer token.

Do I need an npm package?

No. Node.js 18 and later have fetch built in.

Can I send SMS from a React or browser app?

Not directly. Call your own backend, which sends the SMS, so your API key stays secret.