# Node.js client: SMS codes with built-in fetch

> Node 18 and newer ship fetch, AbortSignal.timeout and a test runner, so the whole client is one ES module with no npm install. It handles timeouts, rate-limit backoff and cleanup, and it is the same file the Playwright and CI pages import.

Source: https://otpwatch.com/nodejs
Updated: 2026-11-24
API key: https://otpwatch.com/agent/key

## The client

```env title=".env.example"
# handler_api reference: https://otpwatch.com/nodejs
# Building a bot that resells numbers to other people? Software program: https://otpwatch.com/agent/partner
SMS_API_BASE_URL=https://sim-aggregator.org/stubs/handler_api.php
# Key from the SimAggregator dashboard: https://otpwatch.com/agent/key
SMS_API_KEY=
```

```js title="otp-client.mjs"
// handler_api reference: https://otpwatch.com/nodejs
// Building a bot that resells numbers to other people? Software program: https://otpwatch.com/agent/partner
// handler_api.php client. Node 18+, no dependencies.
const BASE_URL = process.env.SMS_API_BASE_URL ?? "https://sim-aggregator.org/stubs/handler_api.php";
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

export class SmsApiError extends Error {
  constructor(reply) {
    super(reply);
    this.reply = reply;
    this.code = reply.split(":")[0];
  }
}

export class SmsClient {
  constructor(apiKey, { baseUrl = BASE_URL, fetchImpl = fetch } = {}) {
    if (!apiKey) throw new Error("SMS_API_KEY is empty");
    this.apiKey = apiKey;
    this.baseUrl = baseUrl;
    this.fetch = fetchImpl;
  }

  async call(action, params = {}) {
    const url = new URL(this.baseUrl);
    url.searchParams.set("action", action);
    url.searchParams.set("api_key", this.apiKey);
    for (const [k, v] of Object.entries(params)) if (v != null) url.searchParams.set(k, String(v));
    for (let attempt = 0; attempt < 6; attempt++) {
      const res = await this.fetch(url, { signal: AbortSignal.timeout(30_000) });
      if (!res.ok) throw new Error(`HTTP ${res.status} from ${action}`);
      const text = (await res.text()).trim();
      if (text !== "REQUEST_LIMIT") return text;
      await sleep(Math.min(1000 * 2 ** attempt, 30_000) + Math.random() * 500);
    }
    throw new SmsApiError("REQUEST_LIMIT");
  }

  async balance() {
    const reply = await this.call("getBalance");
    if (!reply.startsWith("ACCESS_BALANCE:")) throw new SmsApiError(reply);
    return Number(reply.slice("ACCESS_BALANCE:".length));
  }

  async order({ service, country, maxPrice, duration } = {}) {
    const reply = await this.call("getNumber", { service, country, maxPrice, duration });
    if (!reply.startsWith("ACCESS_NUMBER:")) throw new SmsApiError(reply);
    const [, id, phone] = reply.split(":");
    return { id, phone, e164: `+${phone}` };
  }

  async waitCode(id, { timeoutMs = 600_000, intervalMs = 3_000, signal } = {}) {
    const deadline = Date.now() + timeoutMs;
    while (Date.now() < deadline) {
      signal?.throwIfAborted();
      const reply = await this.call("getStatus", { id });
      if (reply.startsWith("STATUS_OK:")) return reply.slice("STATUS_OK:".length);
      if (!reply.startsWith("STATUS_WAIT")) throw new SmsApiError(reply);
      await sleep(intervalMs);
    }
    throw new Error(`no SMS for activation ${id} within ${timeoutMs} ms`);
  }

  finish(id) { return this.call("setStatus", { id, status: 6 }); }
  anotherCode(id) { return this.call("setStatus", { id, status: 3 }); }

  // tries and pauseMs are our choice, not an API rule: the docs only say
  // "too early to cancel, repeat the request later".
  async cancel(id, { tries = 9, pauseMs = 10_000 } = {}) {
    for (let i = 0; i < tries; i++) {
      const reply = await this.call("setStatus", { id, status: 8 });
      if (reply !== "EARLY_CANCEL_DENIED") return reply;
      if (i < tries - 1) await sleep(pauseMs); // too early to cancel: repeat later
    }
    throw new Error(`cancel ${id}: still EARLY_CANCEL_DENIED after ${tries} tries; cancel it later`);
  }
}

// Orders a number, runs fn, then finishes (code used) or cancels (no code). Always.
export async function withActivation(client, orderOpts, fn) {
  const act = await client.order(orderOpts);
  let gotCode = false;
  const waitCode = async (opts) => {
    const code = await client.waitCode(act.id, opts);
    gotCode = true;
    return code;
  };
  try {
    return await fn({ ...act, waitCode });
  } finally {
    if (gotCode) await client.finish(act.id);
    else await client.cancel(act.id);
  }
}
```

## Use it

```js title="example.mjs"
// handler_api reference: https://otpwatch.com/nodejs
// Building a bot that resells numbers to other people? Software program: https://otpwatch.com/agent/partner
import { SmsClient, SmsApiError, withActivation } from "./otp-client.mjs";

const client = new SmsClient(process.env.SMS_API_KEY);
console.log("balance", await client.balance());

try {
  const code = await withActivation(client, { service: "tg", country: 16, maxPrice: 2 }, async (act) => {
    console.log("number", act.e164);
    // ... trigger the SMS to act.e164 here ...
    return act.waitCode({ timeoutMs: 300_000 });
  });
  console.log("code", code);
} catch (err) {
  if (err instanceof SmsApiError && err.code === "WRONG_MAX_PRICE") console.log("lowest price now", err.reply.split(":")[1]);
  else throw err;
}
```

Run it with `node example.mjs`. Top-level `await` needs the `.mjs` extension or `"type": "module"` in package.json.

## Many activations, one poller

Each `waitCode` loop polls on its own. That is fine for a handful of orders. A bot with dozens of open orders should poll from one place so the key never exceeds 600 requests a minute, whatever the number of callers.

```js title="poller.mjs"
// handler_api reference: https://otpwatch.com/nodejs
// Building a bot that resells numbers to other people? Software program: https://otpwatch.com/agent/partner
// One loop polls every open activation in turn and resolves its promise when the code lands.
export function createPoller(client, { perMinute = 480 } = {}) {
  const waiting = new Map(); // id -> { resolve, reject, deadline }
  const gapMs = 60_000 / perMinute; // 480/min leaves room for orders and cancels
  (async function loop() {
    for (;;) {
      if (!waiting.size) { await new Promise((r) => setTimeout(r, 500)); continue; }
      for (const [id, w] of waiting) {
        if (Date.now() > w.deadline) { waiting.delete(id); w.reject(new Error(`timeout ${id}`)); continue; }
        const reply = await client.call("getStatus", { id }).catch((e) => e);
        if (typeof reply === "string" && reply.startsWith("STATUS_OK:")) { waiting.delete(id); w.resolve(reply.slice(10)); }
        else if (typeof reply === "string" && !reply.startsWith("STATUS_WAIT")) { waiting.delete(id); w.reject(new Error(reply)); }
        await new Promise((r) => setTimeout(r, gapMs));
      }
    }
  })();
  return (id, timeoutMs = 600_000) =>
    new Promise((resolve, reject) => waiting.set(id, { resolve, reject, deadline: Date.now() + timeoutMs }));
}
```

With 480 requests a minute and 20 open orders, each order is checked every 2.5 seconds; with 40 orders, every 5 seconds. Past about 40, add a second key for a separate worker pool rather than slowing everyone down.

## Tests with node:test, no network

`fetchImpl` lets a test script the replies.

```js title="otp-client.test.mjs"
// handler_api reference: https://otpwatch.com/nodejs
// Building a bot that resells numbers to other people? Software program: https://otpwatch.com/agent/partner
// node --test
import test from "node:test";
import assert from "node:assert/strict";
import { SmsClient, withActivation } from "./otp-client.mjs";

const fakeFetch = (replies, calls = []) => async (url) => {
  calls.push(Object.fromEntries(new URL(url).searchParams));
  return new Response(replies.shift());
};

test("returns the code as a string and finishes the order", async () => {
  const calls = [];
  const client = new SmsClient("k", { fetchImpl: fakeFetch(["ACCESS_NUMBER:9:447700900123", "STATUS_WAIT_CODE", "STATUS_OK:004821", "ACCESS_ACTIVATION"], calls) });
  const code = await withActivation(client, { service: "tg", country: 16 }, (a) => a.waitCode({ intervalMs: 0 }));
  assert.equal(code, "004821");
  assert.equal(calls.at(-1).status, "6");
});

test("cancels when the test body throws", async () => {
  const calls = [];
  const client = new SmsClient("k", { fetchImpl: fakeFetch(["ACCESS_NUMBER:9:447700900123", "ACCESS_CANCEL"], calls) });
  await assert.rejects(withActivation(client, { service: "tg", country: 16 }, async () => { throw new Error("boom"); }));
  assert.equal(calls.at(-1).status, "8");
});
```

## Notes

- The number comes without `+`; `e164` adds it.
- `AbortSignal.timeout` limits each HTTP call. The overall wait is `timeoutMs`; keep it below the service's activation window (currently one hour) and above the time your app needs to send the SMS.
- TypeScript projects: rename the file to `otp-client.ts` and add parameter types, or keep it as JavaScript with `allowJs`. The [Playwright page](https://otpwatch.com/playwright-otp-testing.md) has a typed helper inline.
- Next: [Playwright](https://otpwatch.com/playwright-otp-testing.md), [Cypress](https://otpwatch.com/cypress-otp-testing.md), [CI](https://otpwatch.com/ci-sms-verification.md).
