# Send SMS with Node.js (/docs/guides/send-sms-nodejs)

This guide sends an SMS from Node.js (22+) with the `coss` SDK: first in a sandbox, where nothing
is sent or billed, then live from your own registered number.

## Install the SDK [#install-the-sdk]

```package-install
coss
```

Create an API key in your project's **Development** environment (a `coss_test_…` sandbox key), or
run `npx coss-cli init`, and set it as `COSS_API_KEY`. The client reads it when you don't pass `apiKey`.

## Send an SMS from Node.js [#send-an-sms-from-nodejs]

```ts twoslash title="send-sms.ts"
import { Coss } from "coss";

const coss = new Coss({ apiKey: process.env.COSS_API_KEY });

const { data: sms, error } = await coss.sms.send({
  from: "+14155550123",
  to: "+15005550006",
  body: "Your Acme order #1042 has shipped.",
});

if (error) console.error(error.code, error.message);
else console.log(sms.id, sms.status); // "queued"
```

The call returns HTTP `202` with `status: "queued"`; a background worker hands the message to the
carrier. Methods return `{ data, error }` and never throw for API or network failures
([errors](/docs/sdk/errors)).

`from` and `to` are in [E.164](https://en.wikipedia.org/wiki/E.164) form: `+`, the country code,
then the number, without spaces or dashes (`+14155550199`, not `(415) 555-0199`). A `to` that isn't
a phone number is refused with `422` `invalid_phone_number`.

## Test SMS without sending real texts [#test-sms-without-sending-real-texts]

Sandbox keys accept any `from` number, skip the number, country and plan checks, and simulate what a
carrier does. Statuses, events, webhooks and logs all work. These numbers simulate an outcome; any
other number is delivered:

| To             | Simulates                   | Status        |
| -------------- | --------------------------- | ------------- |
| `+15005550006` | Delivered                   | `delivered`   |
| `+15005550001` | A number that can't get SMS | `failed` (`invalid_number`) |
| `+15005550004` | Filtered by the carrier     | `undelivered` (`carrier_filtered`) |
| `+15005550009` | A recipient who opted out   | `failed` (`opted_out`) |
| `+15005550008` | Delivered, then a reply     | `delivered`, then `sms.received` |

See the [SMS simulator](/docs/sms/testing).

## What a live SMS send needs [#what-a-live-sms-send-needs]

Live (`coss_live_…`) keys send only from your organization's own numbers:

1. **A paid plan.** Free organizations can use sandboxes only ([plans](/docs/billing)).
2. **A number.** Owners and admins buy a local or toll-free number on the dashboard's organization
   **SMS** page.
3. **An approved registration.** US carriers only deliver application-to-person SMS from registered
   numbers: local numbers go through US A2P 10DLC (one brand and campaign for the organization),
   toll-free numbers through toll-free verification. coss.com submits both for you; reviews usually
   take a few days. See [numbers and registration](/docs/sms/senders).
4. **An allowed country.** Organizations start with the US and Canada; toll-free numbers only
   send there ([countries](/docs/sms/countries-and-pricing)).

`coss.sms.numbers.list()` returns each number with its `registration_status` and `can_send`. A
live send from a number that isn't yours fails with `sender_not_found`, from one whose registration
isn't approved with `sender_not_ready`, and to a country you don't allow with `country_not_allowed`
(all `422`). See [sending SMS](/docs/sms/sending#numbers) for the rest.

## Segments and encoding [#segments-and-encoding]

Carriers deliver and bill SMS in segments. A body made only of GSM-7 characters fits 160 characters
in one segment (153 per segment when longer). One emoji or curly quote, like the one below, makes
the whole message UCS-2: 70 characters in one segment (67 when longer). A body over 10 segments is
refused. The message's `segments` and `encoding` say how it was counted:

```ts twoslash
import { Coss } from "coss";
const coss = new Coss();
// ---cut---
const { data: sms } = await coss.sms.send({
  from: "+14155550123",
  to: "+14155550101",
  body: "Your table’s ready at Acme Bistro.",
});
console.log(sms?.segments, sms?.encoding); // 1 "ucs2"
```

Live messages are billed per segment at the destination country's rate once they reach a carrier;
failed, suppressed and canceled ones cost nothing. See [pricing](/pricing#sms).

## Avoid duplicate texts with idempotency keys [#avoid-duplicate-texts-with-idempotency-keys]

The SDK sets an idempotency key on every send and reuses it on retries. Pass your own, tied to the
event, so a job that runs twice doesn't text twice: the same key returns the first message.

```ts twoslash
import { Coss } from "coss";
const coss = new Coss();
// ---cut---
await coss.sms.send(
  { from: "+14155550123", to: "+14155550101", body: "Your Acme order #1042 has shipped." },
  { idempotencyKey: "order-1042-shipped" },
);
```

## Track delivery status with webhooks [#track-delivery-status-with-webhooks]

Add a webhook endpoint for the `sms.*` events in the dashboard and verify each request with
`verifyWebhook`. Payloads name the message but never include its text.

```ts twoslash title="server.ts"
import { createServer } from "node:http";
import { verifyWebhook } from "coss";

createServer(async (req, res) => {
  let body = "";
  for await (const chunk of req) body += chunk;
  try {
    const event = await verifyWebhook(body, req.headers, process.env.COSS_WEBHOOK_SECRET!);
    if (event.type === "sms.delivered") console.log("delivered", event.data.sms_id);
    if (event.type === "sms.undelivered" || event.type === "sms.failed") {
      console.log(event.data.sms_id, event.data.failure?.code);
    }
    res.writeHead(200).end("ok");
  } catch {
    res.writeHead(400).end("invalid signature");
  }
}).listen(3000);
```

Not every carrier reports delivery, so a message can stay `sent`. You can also poll with
`coss.sms.get(id)` and `coss.sms.listEvents(id)` ([statuses](/docs/sms/sending#statuses)).

## Handle STOP and opt-outs [#handle-stop-and-opt-outs]

When someone replies STOP (or UNSUBSCRIBE, CANCEL, END, QUIT and a few more), coss.com's SMS
provider sends the confirmation carriers require and their number is suppressed in every live
environment. Sends to it then fail with `opted_out` or `suppressed` and aren't billed; START removes
the opt-out. Listen for `sms.opted_out` to update your own records, or ask
`coss.sms.suppressions.check({ phone_number })` before a send.

Opt-out and carrier-filtering rates count toward your
[reputation](/docs/sms/receiving#opt-outs-and-reputation): text only people who asked, and say who
you are in the first message.

## Next steps [#next-steps]

- [Sending SMS](/docs/sms/sending): statuses, failures, scheduling, suppressions and limits
- [Receiving SMS](/docs/sms/receiving): replies and the `sms.received` webhook
- [Verify phone numbers in a Next.js app](/docs/guides/phone-verification-nextjs)
- [Webhooks](/docs/webhooks) and [SMS pricing](/pricing#sms)
