Developer guide

How to send SMS from Node.js with the JMSURF SMS API

Node.js 18 and later have fetch and crypto.randomUUID built in, so you can send SMS with no SDK and no extra packages. Below are copy-ready examples for single sends, bulk campaigns and webhooks.

Before you start: get an API key

  1. Create a free JMSURF SMS workspace at jmsurfsms.co.ke and confirm your email.
  2. Open Developers, then API keys, and create a test key (starts with jms_test_). Test keys behave like live keys but never deliver or charge; messages are recorded with the status sandbox.
  3. When your code works, create a live key (jms_live_) with only the scopes you need, for example sms:send and sms:read, and top up your wallet with M-Pesa.
  4. Store the key in an environment variable such as JMSURF_API_KEY. Never put it in front-end code or a public repository.

The request in brief

  • POST https://jmsurfsms.co.ke/api/v1/sms/send with header Authorization: Bearer <your key> and a JSON body.
  • to: the phone number, local (07XXXXXXXX or 01XXXXXXXX) or international (+2547XXXXXXXX).
  • message: the text, up to 1,600 characters. 160 plain characters = 1 SMS.
  • reference: a UUID you generate. Sending again with the same reference never sends twice, so retries are safe.
  • sender_id (optional): your approved sender ID; omit it to use your default sender.
  • type (optional): "transactional" for OTPs, receipts and alerts that must reach people who opted out of marketing; "marketing" otherwise.

A successful request returns 202 Accepted with the message id, status queued, number of SMS parts, encoding and cost_kes. A message the network refuses immediately returns 422 with status failed and is refunded. Errors return { "error": { "code": "...", "message": "..." } }.

Send one SMS

sms.mjs
import { randomUUID } from "node:crypto";

export async function sendSms(to, message, reference = randomUUID()) {
  const res = await fetch("https://jmsurfsms.co.ke/api/v1/sms/send", {
    method: "POST",
    headers: {
      Authorization: `Bearer ${process.env.JMSURF_API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ to, message, reference, type: "transactional" }),
    signal: AbortSignal.timeout(30_000),
  });
  const body = await res.json();
  if (!res.ok && res.status !== 422) {
    throw new Error(`${res.status} ${body.error?.code}: ${body.error?.message}`);
  }
  return body; // { id, reference, to, status, segments, encoding, cost_kes, sender_id, test }
}

const sms = await sendSms("07XXXXXXXX", "Your order #1024 is out for delivery.");
console.log(sms.id, sms.status, sms.cost_kes);

Retry safely

Save the reference with your own record before calling the API. If the request times out or you get a 429 or 503, call again with the same reference: JMSURF SMS returns the original message instead of sending a second one. A reference reused for a different message returns 409 reference_conflict.

retry
async function sendWithRetry(to, message, reference, attempts = 3) {
  for (let i = 1; ; i++) {
    try {
      return await sendSms(to, message, reference);
    } catch (error) {
      if (i >= attempts || !/^(429|503|5\d\d)/.test(error.message)) throw error;
      await new Promise((r) => setTimeout(r, 60_000)); // Retry-After is 60 s
    }
  }
}

Bulk campaign

bulk.mjs
const res = await fetch("https://jmsurfsms.co.ke/api/v1/sms/bulk", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.JMSURF_API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    name: "Weekend offer",
    message: "Hi {first_name|there}, 10% off this weekend: {link}",
    recipients: customers.map((c) => ({ phone: c.phone, name: c.name, fields: { link: c.link } })),
    shorten_links: true,
  }),
});
const campaign = await res.json();
// 202: { campaign_id, recipients, skipped: { duplicates, invalid, blocked, unsupported_destination }, estimated_cost_kes, send_at, test }

Follow progress with GET /api/v1/campaigns/{id}, which returns recipients, pending, accepted, delivered, failed and cost so far.

Express webhook for delivery reports and replies

webhook.mjs
import express from "express";
import { createHmac, timingSafeEqual } from "node:crypto";

const app = express();
app.post("/jmsurf/webhook", express.raw({ type: "application/json" }), (req, res) => {
  const expected = "sha256=" + createHmac("sha256", process.env.JMSURF_WEBHOOK_SECRET)
    .update(req.body).digest("hex");
  const given = req.get("x-jmsurf-signature") ?? "";
  if (given.length !== expected.length || !timingSafeEqual(Buffer.from(given), Buffer.from(expected))) {
    return res.sendStatus(401);
  }
  const { id, event, data } = JSON.parse(req.body.toString("utf8"));
  // de-duplicate on id (also sent as x-jmsurf-event-id), then handle:
  if (event === "sms.delivered") markDelivered(data.reference);
  if (event === "sms.inbound") saveReply(data.from, data.message);
  res.sendStatus(200);
});
app.listen(3000);

Errors to handle

HTTPerror.codeWhat to do
400invalid_request / invalid_recipientFix the body or phone number; do not retry unchanged
401unauthorized / invalid_keyCheck the key and the Bearer header
402insufficient_creditTop up the wallet
403insufficient_scope / ip_not_allowedAdd the scope or allow your server's IP on the key
409reference_conflictThe reference was used for a different message; generate a new one
422recipient_blocked / sender_not_approvedThe message cannot be sent as requested
429rate_limitedWait 60 seconds (Retry-After header) and retry with the same reference
503provider_credit / sending_pausedHold the message and retry later with the same reference

Start sending today

Create a free workspace, top up with M-Pesa and send your first message at KES 0.40 per SMS. Questions first? Call or WhatsApp +254 712 504 593 or email [email protected].

Make every message count.

Start with a free workspace. Add your audience, top up with M-Pesa and keep your customers in the conversation.

Create your workspace