# SMS verification in Node.js

A complete ES module that uses the built-in fetch of Node.js 18+: buy a temporary number, wait for the code and close the order, with TypeScript types for the response.

## How do I receive an SMS verification code in Node.js?

Call fetch with the X-Api-Key header: POST /v1/orders to get a number, poll GET /v1/orders/{id} every 4 seconds until messages has the SMS, read messages.at(-1).code and POST finish. Cancel if nothing arrives so the frozen amount is released.

## Setup

- Node.js 18 or newer (global fetch, top-level await in .mjs files).
- No dependencies to install.
- Export your key: export SMSNITRO_API_KEY=...

## Complete script

**activation.mjs**

```javascript
// Node.js 18+ (global fetch). Save as activation.mjs and run: node activation.mjs
const API = "https://smsnitro.com/api/v1";
const headers = { "X-Api-Key": process.env.SMSNITRO_API_KEY, "Content-Type": "application/json" };

async function api(method, path, body) {
  const res = await fetch(API + path, { method, headers, body: body && JSON.stringify(body) });
  const data = await res.json();
  if (!res.ok) throw new Error(`${res.status}: ${data.detail}`);
  return data;
}

const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

const { balance } = await api("GET", "/balance");
console.log("Balance:", balance, "USD");

let order = await api("POST", "/orders", { product: "telegram", country: "usa" });
console.log("Number:", order.phone, "order", order.id);

const deadline = Date.now() + 600_000; // numbers stay reserved for up to 20 minutes
let done = false;
while (!done && Date.now() < deadline) {
  order = await api("GET", `/orders/${order.id}`);
  if (order.messages.length) {
    console.log("Code:", order.messages.at(-1).code);
    await api("POST", `/orders/${order.id}/finish`);
    done = true;
  } else if (["CANCELED", "TIMEOUT", "BANNED", "FINISHED"].includes(order.status)) {
    console.log("Ended without SMS:", order.status, "(not charged)");
    done = true;
  } else {
    await sleep(4000); // poll every 3 to 5 seconds
  }
}
if (!done) {
  await api("POST", `/orders/${order.id}/cancel`); // refund the frozen amount
  console.log("No SMS: cancelled and refunded");
}
```

## TypeScript types

The order object returned by every order endpoint. Prices are decimal strings: convert with Number() only for display.

**types.ts**

```typescript
type Sms = { sender: string; text: string; code: string; received_at: string };
type Order = {
  id: number;
  phone: string;
  status: "PENDING" | "RECEIVED" | "FINISHED" | "CANCELED" | "TIMEOUT" | "BANNED";
  price: string;          // decimal string, USD
  expires: string | null; // ISO 8601, UTC
  messages: Sms[];
  awaiting_resend: boolean;
  server: number;
};
```

Source: https://smsnitro.com/developers/nodejs
