Send a WhatsApp message from Node.js with one fetch POST to https://graph.facebook.com/v26.0/<PHONE_NUMBER_ID>/messages, a Bearer token and a JSON body. Node.js 22 or later ships everything the script below uses: global fetch, AbortSignal.timeout and the --env-file flag. There is no SDK and no npm install. A response with messages[0].id means Meta accepted the message. Delivery is reported later, by webhook.
Use Node.js 22 or later
Node’s release page marks v18 and v20 as end of life and lists v22, v24 and v26 as the LTS lines. It also says “Production applications should only use Active LTS or Maintenance LTS releases” (Node.js releases, accessed 2026-11-04). That makes v22 the floor, even though fetch itself has been global since v18.0.0 and “No longer experimental” since v21.0.0 (Node.js globals).
The --env-file flag “Loads environment variables from a file relative to the current directory, making them available to applications on process.env.” It was added in v20.6.0 and left experimental status in v22.21.0 and v24.10.0 (Node.js CLI). You don’t need the dotenv package.
The script needs a token, a phone number ID and a Graph API version. The Python version of this guide explains where each comes from and why v26.0. For a token that outlives a test session, use a system user token from Cloud API access tokens. The phone number ID of Meta’s test number is in the test number guide. Put the three values in .env next to the script:
WHATSAPP_TOKEN=ACCESS_TOKEN
PHONE_NUMBER_ID=PHONE_NUMBER_ID
GRAPH_VERSION=v26.0
The script
Save this as send.mjs. The .mjs extension makes it an ES module, which allows the top-level await. It sends a text, a template or an image by link, retries temporary errors and prints the message ID.
// send.mjs: node --env-file=.env send.mjs text|template|image TO ...
import { setTimeout as sleep } from 'node:timers/promises';
const TOKEN = process.env.WHATSAPP_TOKEN;
const PHONE_NUMBER_ID = process.env.PHONE_NUMBER_ID;
const GRAPH_VERSION = process.env.GRAPH_VERSION || 'v26.0';
if (!TOKEN || !PHONE_NUMBER_ID) {
console.error('Set WHATSAPP_TOKEN and PHONE_NUMBER_ID in .env');
process.exit(1);
}
const MESSAGES_URL = `https://graph.facebook.com/${GRAPH_VERSION}/${PHONE_NUMBER_ID}/messages`;
// Codes Meta's error reference marks as temporary or "try again later"
const RETRY_CODES = new Set([2, 4, 80007, 130429, 131000, 131016, 131056, 133004]);
class GraphError extends Error {
constructor(status, error, rawBody) {
const details = error?.error_data?.details ?? '';
super(error
? `HTTP ${status}, code ${error.code}: ${error.message} ${details}`.trim()
: `HTTP ${status}, no Graph error JSON: ${rawBody.slice(0, 200)}`);
this.name = 'GraphError';
this.status = status;
this.code = error?.code;
this.details = details;
this.fbtraceId = error?.fbtrace_id;
}
}
async function post(payload) {
const res = await fetch(MESSAGES_URL, {
method: 'POST',
headers: { Authorization: `Bearer ${TOKEN}`, 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
signal: AbortSignal.timeout(10_000),
});
const rawBody = await res.text();
let data = null;
try {
data = JSON.parse(rawBody);
} catch {
// a proxy or gateway error page can be HTML
}
if (res.ok && data && !data.error) return data;
throw new GraphError(res.status, data?.error, rawBody);
}
function retryable(err) {
if (err.name === 'TimeoutError') return true; // this script's choice
if (!(err instanceof GraphError)) return false; // network failure or a bug
if (err.code !== undefined) return RETRY_CODES.has(err.code);
return err.status >= 500; // this script's choice
}
async function send(payload, attempts = 4) {
for (let attempt = 0; ; attempt++) {
try {
return await post(payload);
} catch (err) {
if (!retryable(err) || attempt === attempts - 1) throw err;
const wait = 1000 * 2 ** attempt + Math.random() * 250;
console.error(`retry ${attempt + 1} in ${Math.round(wait)} ms: ${err.message}`);
await sleep(wait);
}
}
}
const base = (to, type) => ({ messaging_product: 'whatsapp', recipient_type: 'individual', to, type });
function textPayload(to, body) {
return { ...base(to, 'text'), text: { preview_url: false, body } };
}
function templatePayload(to, name, language, params) {
const template = { name, language: { code: language } };
if (params.length) {
template.components = [{
type: 'body',
parameters: params.map((p) => {
const i = p.indexOf('=');
return i > 0
? { type: 'text', parameter_name: p.slice(0, i), text: p.slice(i + 1) }
: { type: 'text', text: p };
}),
}];
}
return { ...base(to, 'template'), template };
}
function imagePayload(to, link, caption) {
const image = { link };
if (caption) image.caption = caption;
return { ...base(to, 'image'), image };
}
const [kind, to, ...rest] = process.argv.slice(2);
let payload;
if (kind === 'text' && to && rest.length >= 1) payload = textPayload(to, rest[0]);
else if (kind === 'template' && to && rest.length >= 2) payload = templatePayload(to, rest[0], rest[1], rest.slice(2));
else if (kind === 'image' && to && rest.length >= 1) payload = imagePayload(to, rest[0], rest[1]);
else {
console.error('usage: send.mjs text TO BODY | template TO NAME LANGUAGE [PARAMS...] | image TO URL [CAPTION]');
process.exit(1);
}
try {
const data = await send(payload);
const message = data.messages[0];
console.log('accepted:', message.id, message.message_status ?? '');
console.log('wa_id:', data.contacts?.[0]?.wa_id ?? '');
} catch (err) {
console.error(err.message);
if (err.cause) console.error('cause:', err.cause.message ?? err.cause);
if (err.fbtraceId) console.error('fbtrace_id:', err.fbtraceId);
if (err.code === 131047) console.error('Window closed: send an approved template instead.');
if (err.code === 190) console.error('Token expired: create a new access token.');
process.exitCode = 1;
}
Check the response status yourself
fetch resolves on any HTTP status, 400 and 500 included. It rejects only when the request never completes, such as on a DNS or connection failure. A Graph error therefore arrives as a normal response, and post() has to test res.ok and look for an error object itself.
The body is read with res.text() and parsed inside a try. A load balancer or proxy in front of Graph can answer with an HTML page. Then res.json() would throw a parse error that hides the HTTP status. GraphError keeps the status, error.code, error.error_data.details and fbtrace_id. The shape of Meta’s error JSON is shown in the Python guide.
Which errors the script retries
Meta says to “build your app’s error handling logic around code values and details payload properties” (Meta error codes, accessed 2026-11-04). The error reference gives no HTTP status for most codes and documents no Retry-After header. The script therefore never looks at 429. It retries the codes Meta marks as temporary or “try again later”:
| Code | Meta’s details |
|---|---|
| 130429 | “Cloud API message throughput has been reached.” |
| 131056 | “Too many messages sent from the sender phone number to the same recipient phone number in a short period of time.” |
| 131000 | “Message failed to send due to an unknown error.” |
| 131016 | “A service is temporarily unavailable.” |
| 133004 | “Server is temporarily unavailable.” |
| 2 | “Temporary due to downtime or due to being overloaded.” |
| 4 | “The app has reached its API call rate limit.” |
| 80007 | “The WhatsApp Business Account has reached its rate limit.” |
Two more retry cases are this script’s own choice, not Meta’s guidance. One is an HTTP 5xx with no Graph error JSON in the body. The other is a TimeoutError from AbortSignal.timeout(10_000), which “Returns a new AbortSignal which will be aborted in delay milliseconds” (Node.js globals). Meta documents no client timeout, so the 10 seconds is arbitrary.
A timeout retry can send the message twice. Your side stopped waiting, but Meta may have accepted the first request. If a duplicate costs you more than a missing message, drop the TimeoutError line and reconcile from status webhooks instead.
Everything else fails at once. A network failure (fetch’s TypeError) also fails at once. Codes 131047, 190, 100, 131008, 131009, 131021, 368, 131026 and 131048 need a change to the request, the token or the account. The 1, 2 and 4 second waits with up to 250 ms of jitter are placeholders. Meta’s pacing for 130429 and 131056 is in Cloud API rate limits.
Send text inside the window
node --env-file=.env send.mjs text +16505551234 "Your order shipped"
The payload matches Meta’s text message sample with preview_url off (Meta text messages, accessed 2026-11-04). body takes up to 4096 characters. Free-form text only goes through while the customer service window is open. Outside it Meta returns 131047, and the script prints the template hint (error 131047).
Send a template outside the window
node --env-file=.env send.mjs template +16505551234 order_confirmation en_US first_name=Jessica order_number=SKBUP2-4CPIG9
This builds the body of Meta’s order_confirmation example from the template overview (Meta template fundamentals, accessed 2026-11-04). Replace the name and values with an approved template of your own. The argument rule is the same as in the Python script. name=value becomes a named parameter and a bare value becomes a positional one. A positional value that contains = is read as named, so change the parser if your values can contain one. Template variables covers header and button parameters.
Send an image by link
node --env-file=.env send.mjs image +16505551234 https://YOUR_DOMAIN/photo.jpg "Succulent of the week"
Meta’s request syntax for images puts HTML comments inside the JSON, so it doesn’t parse as published. With the comments removed and the id line dropped for hosted media, the body the script sends is:
{
"messaging_product": "whatsapp",
"recipient_type": "individual",
"to": "+16505551234",
"type": "image",
"image": {
"link": "https://YOUR_DOMAIN/photo.jpg",
"caption": "Succulent of the week"
}
}
link is the “URL of the media asset hosted on your public server”. Meta adds “For better performance, we recommend using id and an uploaded media asset ID instead” (Meta image messages, accessed 2026-11-04). To switch, replace { link } in imagePayload with { id: MEDIA_ID }. The caption takes up to 1024 characters. JPEG, PNG and static WebP are accepted up to 5 MB each, and images over 4,096 pixels on an edge are rejected. Other media types are in supported types and size limits.
When you send by link, the Cloud API “internally caches the asset for 10 minutes” (Meta send messages, accessed 2026-11-04). Later sends with the same URL reuse it. If you replace the file behind a URL, change the URL too, or recipients can get the old image for up to 10 minutes.
A broken link usually fails after the call, so the script still prints a message ID. The failure arrives as a failed status webhook. For media, Meta lists code 131053, “Unable to upload the media used in the message.” Meta’s fix is to read error.error_data.details in that webhook and check the MIME type.
Read the response and watch the webhook
The script prints messages[0].id and contacts[0].wa_id. Store the ID, because every status webhook for the message carries it. The message_status values and the wa_id caveat are covered in the Python guide.
Meta asks that “you monitor both the Graph API response and the messages webhook for error handling” (Meta error codes, accessed 2026-11-04). The 131053 case above usually doesn’t reach the script’s catch. A webhook receiver in Node is in Receive WhatsApp webhooks with Express. The failed payload is described in status webhooks.
Z-API Omni team