Send SMS from Node.js with fetch, no SDK and no Twilio account
Node 18 and later has fetch built in, so sending a text from your own phone takes no npm install at all. Then delivery status, safe retries, a list where everyone gets their own words, and replies, all tested.
Sparetext
8 min read · Nov 11, 2026
Most "send SMS from Node.js" tutorials start with npm install twilio, then a paid number, then a registration form before US carriers let it text anyone. If your texts go to people who already know you, you can skip all three, and you don't even need a package: Node has had fetch built in since version 18.
Sparetext turns the phone you already own into an SMS gateway with a plain HTTP API. Your script talks to our server, and the text goes out from your phone, on your number. Every sample below ran on 11 November on Node 25, against a test copy of Sparetext with a simulated phone on the other end.
What you need
- A Sparetext account. Free is 1 phone and 300 texts a month.
- An Android phone with the Sparetext app, paired in the dashboard. An iPhone works too, through Sparetext for Mac or a Shortcut (the iPhone guide).
- An API key from the API keys page, in an environment variable:
export SPARETEXT_API_KEY=spt_live_... - Node 18 or later. Check with
node --version. Nothing to install.
Send your first text
Save this as send.mjs. The .mjs ending lets you use await at the top of the file without wrapping anything in a function.
const API = "https://sparetext.dev/api/v1";
const res = await fetch(`${API}/messages`, {
method: "POST",
headers: {
"x-api-key": process.env.SPARETEXT_API_KEY,
"content-type": "application/json",
},
body: JSON.stringify({ to: "+12025550181", text: "Your table for 2 is ready. See you soon!" }),
signal: AbortSignal.timeout(15_000),
});
const body = await res.json();
if (!res.ok) throw new Error(`${res.status} ${body.error.code}: ${body.error.message}`);
console.log(body);Put your own number in to, with its country code, and run node send.mjs. Your phone sends the text a moment later. The answer looks like this, trimmed:
{
"batchId": "b_ghh5qxr8q54m",
"messages": [
{
"id": "msg_20261111_h9xtif78",
"contact": "+12025550181",
"status": "queued",
"deviceName": "Pixel 8 (simulated)",
"source": "api"
}
],
"estimatedCompletionAt": "2026-11-11T07:36:02.758Z"
}Two small things in there are easy to miss. fetch never throws on a 400 or a 500, it only throws when the network fails, so you have to check res.ok yourself. And fetch has no timeout by default, so without AbortSignal.timeout a stuck connection can hang your script forever.
When something's wrong, every error comes back the same way, with a code you can test in code and a message for people. With a bad key, our test printed 401 unauthorized: That key or token is not valid. It may have been revoked.
Check that it arrived
queued means the text is waiting for your phone. It then moves to dispatched (the phone has it), sent, and delivered if your carrier sends delivery reports. A text that goes wrong ends at failed, with the reason in error. This script sends a text and waits for it to settle:
const API = "https://sparetext.dev/api/v1";
const headers = {
"x-api-key": process.env.SPARETEXT_API_KEY,
"content-type": "application/json",
};
async function call(method, path, payload) {
const res = await fetch(API + path, {
method,
headers,
body: payload && JSON.stringify(payload),
signal: AbortSignal.timeout(15_000),
});
const body = await res.json();
if (!res.ok) throw new Error(`${res.status} ${body.error.code}: ${body.error.message}`);
return body;
}
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function waitForDelivery(id, timeoutMs = 120_000) {
const deadline = Date.now() + timeoutMs;
while (true) {
const { message } = await call("GET", `/messages/${id}`);
if (["delivered", "failed", "canceled"].includes(message.status) || Date.now() > deadline) return message;
await sleep(3_000);
}
}
const { messages } = await call("POST", "/messages", {
to: "+12025550182",
text: "Your table for 2 is ready. See you soon!",
});
console.log(messages[0].id, messages[0].status);
const final = await waitForDelivery(messages[0].id);
console.log(final.status, final.error ?? "");Against the simulated phone it printed queued, then delivered on the first check three seconds later. A real phone on a real network takes longer, and some carriers never send a delivery report at all, so a text can rest at sent. That's why the loop gives up after two minutes and hands back what it has.
Retry without texting someone twice
Here's the thing about retries and SMS. If your request times out, you don't know whether the text was queued. Send again blindly and your customer might get the same text twice, which for a one-time code or a payment reminder looks broken.
The fix is an Idempotency-Key header: any unique string you make up. Send the same key again and Sparetext hands back the first answer instead of queuing a second text. Keys are kept for 24 hours. This helper makes one key per text, keeps it across tries, and also waits out a 429 when you send too fast:
import { randomUUID } from "node:crypto";
const API = "https://sparetext.dev/api/v1";
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
export async function sendText(payload, { tries = 4 } = {}) {
const key = randomUUID(); // the same key on every try, so a retry can't send twice
for (let attempt = 1; ; attempt++) {
let res;
try {
res = await fetch(`${API}/messages`, {
method: "POST",
headers: {
"x-api-key": process.env.SPARETEXT_API_KEY,
"content-type": "application/json",
"idempotency-key": key,
},
body: JSON.stringify(payload),
signal: AbortSignal.timeout(15_000),
});
} catch (err) {
if (attempt >= tries) throw err; // timeout or network error: try again with the same key
await sleep(1_000 * attempt);
continue;
}
const body = await res.json();
if (res.ok) return body;
const wait = res.headers.get("retry-after");
if (res.status === 429 && wait && attempt < tries) {
await sleep(Number(wait) * 1_000);
continue;
}
throw new Error(`${res.status} ${body.error.code}: ${body.error.message}`);
}
}We checked both halves. The same key sent twice came back with the same message id, and only one text was queued. The same key with different words was refused with 422 idempotency_mismatch, so a bug in your code can't quietly reuse a key for another text.
Then the rate limit. An account can make 15 send requests every 5 seconds, and past that the API answers 429 rate_limited with a Retry-After header in seconds. We sent 20 texts one after another through sendText. It was told to wait once, for 2 seconds, and all 20 went through in about two and a half seconds.
One 429 has no Retry-After on purpose: key_daily_limit, when a key has used up the texts you allowed it for the day. The helper throws on that one instead of retrying until midnight. You set that limit per key on the API keys page.
Text a list, each person their own words
Say tomorrow's bookings are in a bookings.json file, an array of name, phone and time. One request can carry up to 100 people, each with their own text:
import { readFile } from "node:fs/promises";
const API = "https://sparetext.dev/api/v1";
const bookings = JSON.parse(await readFile("bookings.json", "utf8"));
const messages = bookings.map((b) => ({
to: b.phone,
text: `Hi ${b.name}, see you tomorrow at ${b.time}. Reply YES to confirm.`,
}));
for (let start = 0; start < messages.length; start += 100) {
const res = await fetch(`${API}/messages`, {
method: "POST",
headers: {
"x-api-key": process.env.SPARETEXT_API_KEY,
"content-type": "application/json",
},
body: JSON.stringify({ messages: messages.slice(start, start + 100) }),
signal: AbortSignal.timeout(30_000),
});
const batch = await res.json();
if (!res.ok) throw new Error(`${res.status} ${batch.error.code}: ${batch.error.message}`);
console.log(batch.batchId, batch.messages.length, "queued, last one out about", batch.estimatedCompletionAt);
}Resist the urge to Promise.all a thousand single sends. You'd hit the rate limit in the first second, and your phone sends at about 30 texts a minute anyway, under Android's own limit. One request per hundred people does the same job, and estimatedCompletionAt tells you when the last one should go.
Read the replies
Replies land in the same API. This prints everything that came in over the last ten minutes:
const API = "https://sparetext.dev/api/v1";
const since = new Date(Date.now() - 10 * 60_000).toISOString();
const url = new URL(`${API}/messages`);
url.search = new URLSearchParams({ direction: "inbound", since });
const res = await fetch(url, {
headers: { "x-api-key": process.env.SPARETEXT_API_KEY },
signal: AbortSignal.timeout(15_000),
});
const body = await res.json();
if (!res.ok) throw new Error(`${res.status} ${body.error.code}: ${body.error.message}`);
for (const text of body.messages) console.log(text.contact, "said:", text.text);In our test, the three made-up guests from bookings.json answered YES and the script printed all three. Polling is fine for a script you run by hand. For a bot that answers within seconds, have Sparetext call your server instead: the reply bot post builds one on Node's own http module, signature check and all.
Send it later
Add scheduledAt with a time zone and the text waits as scheduled until then. DELETE /messages/{id} cancels it if plans change. We scheduled one for 9am New York time, got back scheduled with the time in UTC, and cancelled it with a 204.
body: JSON.stringify({
to: "+12025550188",
text: "Reminder: your appointment is tomorrow at 9.",
scheduledAt: "2026-11-12T09:00:00-05:00",
}),What this can't do
A phone is the right tool for texts to people who know you: reminders, confirmations, alerts to your team, replies to customers. For login codes there's a ready-made verify endpoint with the same two calls in Node, so you don't store codes yourself.
It's the wrong tool for marketing to a list that didn't ask. Carriers filter business texts sent by software even from a personal number, and the 10DLC post explains why. An iPhone can't send silently in the background the way Android can, and only Android phones get carrier delivery reports, so on an iPhone sent is as far as a text goes. On plans, Free covers 300 texts a month and Pro 10,000 on up to 5 phones (pricing). A long text counts once against your plan, however many parts it takes.
Writing Python instead? The Python post has the same steps with requests, plus a CSV list. There are also versions for PHP, Go, Ruby, Java, and shell scripts with curl.
Try it with your own number
Make a key on the API keys page, pair your phone, and run node send.mjs with your own number in to. When your pocket buzzes, swap the plain fetch for sendText from safe-send.mjs and wire it into your app.
More scripts to start from are in our public examples repo, sparetext-examples/node: send, a different text per person, wait for the reply, read new texts in order and a signed webhook receiver. They need Node 18 or newer and no packages.
node.jsjavascriptsend smssms apifetchtutorial
Try it with the phone you have
Free for 1 phone and 300 texts a month. Pair it in about two minutes.
Responses
Sign in or create an account to respond.