SMSNET
Guide

How to Send an SMS from Node.js

To send an SMS from Node.js, POST JSON with to and body to https://smsnet.net/api/v1/messages/send with your key in the X-API-Key header, using the built-in fetch in Node 18 or newer. The response returns a message_id and quota, and the text leaves from your connected Android phone. No SDK install needed.

Save each example below with an .mjs extension and run it with node on Node 18 or newer, which ships a global fetch and top level await.

What do I need before the first call?

Two things: a connected phone and an API key. Install the SMSNET Gateway app on any Android 8.0 or newer phone with a SIM, sign in, and copy the key from the last setup screen into an environment variable. The Android gateway guide shows every screen. The free plan is enough to build against: 300 messages a month, 20 a day, and replies are never counted. Numbers go in E.164 format (+15551234567).

How do I send an SMS with fetch?

// send.mjs, run with: node send.mjs (Node 18 or newer)
const API = "https://smsnet.net/api/v1";
const KEY = process.env.SMSNET_API_KEY;

async function sendSms(to, body, transactional = false) {
  const res = await fetch(`${API}/messages/send`, {
    method: "POST",
    headers: { "X-API-Key": KEY, "Content-Type": "application/json" },
    body: JSON.stringify({ to, body, transactional }),
  });
  if (res.status === 429) {
    const detail = await res.json().catch(() => ({}));
    throw new Error(`Allowance reached: ${detail.error || "wait for the window or upgrade the plan."}`);
  }
  if (res.status === 403) {
    const detail = await res.json().catch(() => ({}));
    throw new Error(`Not delivered: ${detail.error || "the recipient opted out. Do not retry."}`);
  }
  if (!res.ok) {
    const detail = await res.json().catch(() => ({}));
    throw new Error(`Send failed with status ${res.status}: ${detail.error || res.statusText}`);
  }
  return res.json();
}

const result = await sendSms("+15551234567", "Your table is ready. Reply STOP to opt out.");
console.log(result.message_id, result.quota.day);

A successful response carries message_id, conversation_id, and a quota object with used and limit for the day and month, so the code can slow down before it hits the wall. Set transactional to true only for a message the recipient is waiting on right now, such as a login code. The SMS API pillar documents every endpoint, and the Python and curl versions show the same call in other syntax.

How should the code handle errors?

StatusWhenWhat to do
400Missing to or body, or no phone connected to the accountFix the request, or connect a phone
401Missing or wrong key; the error says whether the key was rotatedLoad the key from the environment, rotate if needed
403The recipient opted out; the error names the date and the words they usedDo not retry; remove them from your list
429Monthly or daily allowance reached, including the headroomWait for the window, or upgrade the plan

The sender above already separates 429 from 403 because the two need opposite reactions: a 429 means slow down and try later, while a 403 means never try that recipient again. Log the response body on any other status; it names the exact field or precondition that failed.

How do I read replies by polling?

Polling needs no public URL. Pass back the next_cursor from each response as since on the next call, so nothing is missed or repeated:

// poll.mjs, run with: node poll.mjs (Node 18 or newer)
const API = "https://smsnet.net/api/v1";
const KEY = process.env.SMSNET_API_KEY;
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

let cursor = null;
for (;;) {
  const params = new URLSearchParams({ direction: "inbound", limit: "100" });
  if (cursor) params.set("since", cursor);
  const res = await fetch(`${API}/messages?${params}`, { headers: { "X-API-Key": KEY } });
  if (!res.ok) throw new Error(`Poll failed with status ${res.status}`);
  const page = await res.json();
  for (const m of page.messages) console.log(m.from_number, m.body, m.conversation_id);
  cursor = page.next_cursor || cursor;
  if (!page.has_more) await sleep(10000);
}

How do I verify webhooks in Node?

Register your HTTPS endpoint once with PUT /api/v1/webhooks carrying {"url": "..."}, keep the secret from the response, and send a test event with POST /api/v1/webhooks/test. Then verify the HMAC-SHA256 signature on every delivery with crypto.timingSafeEqual, comparing against the raw body before anything parses it:

// webhook.mjs, run with: node webhook.mjs (Node 18 or newer)
import http from "node:http";
import crypto from "node:crypto";

const SECRET = process.env.SMSNET_WEBHOOK_SECRET;

function valid(req, raw) {
  const ts = req.headers["x-smsnet-timestamp"] || "";
  const sig = req.headers["x-smsnet-signature"] || "";
  if (Math.abs(Date.now() / 1000 - Number(ts || 0)) > 300) return false;
  const expected = `v1=${crypto.createHmac("sha256", SECRET).update(`${ts}.${raw}`).digest("hex")}`;
  const a = Buffer.from(expected, "utf8");
  const b = Buffer.from(sig, "utf8");
  return a.length === b.length && crypto.timingSafeEqual(a, b);
}

const server = http.createServer((req, res) => {
  let raw = "";
  req.on("data", (chunk) => { raw += chunk; });
  req.on("end", () => {
    if (req.method !== "POST" || !valid(req, raw)) {
      res.writeHead(400, { "Content-Type": "text/plain" });
      res.end("bad signature");
      return;
    }
    const event = JSON.parse(raw);
    if (event.event === "message.received") console.log("reply:", event.data.from, event.data.body);
    if (event.event === "message.status") console.log(event.data.message_id, "is now", event.data.status);
    res.writeHead(200, { "Content-Type": "text/plain" });
    res.end("ok");
  });
});

server.listen(3000, () => console.log("listening on http://localhost:3000"));

Dedupe on the X-SMSNET-Delivery header, which stays stable across retries. Everything here runs on the free plan; the endpoint reference is the SMS API pillar.

The three Node.js paths side by side: send with fetch, poll with a cursor, verify with timingSafeEqual.

The three Node.js code paths: send, poll, and verify webhooks Three horizontal lanes. Lane one sends with fetch POST and gets back message_id plus quota. Lane two polls GET messages with a since cursor in a loop and prints replies. Lane three registers a webhook once and verifies each delivery with timingSafeEqual over the raw body. Three small programs cover the whole Node.js integration Send once, poll in a loop, verify pushes. All three use only built in fetch, http and crypto. 1 2 3 fetch POST /messages/send GET /messages poll loop webhook verify sendSms(to, body) with X-API-Key since = next_cursor, sleep 10 s HMAC check with timingSafeEqual returns message_id + quota day and month used vs limit prints from_number, body nothing missed or repeated accepts message.received raw body, timestamp, 5 min skew Start with lane 1, add lane 2 for a script, or lane 3 for a server. Error handling splits 429 (wait) from 403 (never retry).
Three lane diagram: lane one sends with fetch POST and returns message_id plus quota, lane two polls GET /api/v1/messages with a since cursor in a loop, and lane three verifies webhook deliveries with timingSafeEqual over the raw body.

FAQ

How do I send an SMS from Node.js?

POST JSON with to and body to https://smsnet.net/api/v1/messages/send using the global fetch in Node 18 or newer, with your key in the X-API-Key header. The response returns a message_id and your remaining quota. Save the example as an .mjs file so top level await runs.

Do I need an SDK or an extra package?

No. The examples use only the built-in fetch plus the node:http and node:crypto modules, so nothing needs installing. Save files with an .mjs extension and run them with node on Node 18 or newer.

How do I handle rate limits in Node?

Check for status 429 after the POST and back off until the window resets instead of retrying in a tight loop. The quota object in every send response shows used and limit for the day and month, so the code can slow down before it hits the wall.

What does a 403 response mean?

The recipient opted out, and the error names the date and the words they used. Do not retry and remove them from the list.

How do I read SMS replies in Node?

Poll GET /api/v1/messages?direction=inbound with the next_cursor from the previous call, or register an HTTPS webhook and verify each delivery with crypto.timingSafeEqual over the timestamp, a dot, and the raw body.

What phone number does the recipient see?

The number of the SIM in your connected Android phone. It is your own number, so replies come straight back to you and the conversation stays in one thread.

This is a spoke of What Is an SMS API and How to Use One. Siblings: Send an SMS from Python and Send an SMS with curl. The phone comes from Turn Your Android Phone into an SMS Gateway; the agent route is What Is an MCP Server for SMS?.

Send your first message today

Free plan, no card: 400 messages a month from your own number, with the API, webhooks and MCP included.

Get the app See pricing

Get it on Google Play

Written by , who builds SMSNET. Product facts on this page are checked against the live pricing page and the running API on the date shown above.