---
title: "Send SMS from a Replit app with Bird"
description: "Send SMS verification codes from an app on Replit through the Bird SMS API, with the API key in Replit Secrets and a daily spend limit per country."
canonical: "https://bird.com/docs/knowledge-base/integrations/replit"
---

# Send SMS from a Replit app with Bird

Send SMS from an app you build on [Replit](https://replit.com) by calling the Bird SMS API from the app's server code. This guide sends a verification code with a built-in Bird template. The template supplies the message text and a shared sender, so you need no sender ID and no sender registration.

Replit's connector list has no Bird connector. Two connections exist, and they do different jobs:

- **While you build:** add Bird's MCP server to Replit, so Agent can read and configure your Bird workspace. [Bird for Replit](/ai/replit) shows that setup.
- **While your app runs:** your app calls the Bird API with an API key held in Replit Secrets. This guide covers that path.

## Choose the right path

This guide sends verification codes that your app creates and checks itself, through the SMS API. Use another path in this case:

- **You want Bird to create and check the code.** Use [Verify](/docs/guides/verify/overview) from the same server-side code. Bird generates the code, expires it, limits wrong attempts, and applies a resend cooldown, in two API calls, so your app stores no code. Verify has its own destination list, where every country starts enabled: turn off the countries you do not serve.

Stay with this guide when your app keeps its own codes. The SMS API sends only to the countries you enable, and each country can have a daily spend limit.

## Before you start

You need a Replit project with server code, a Bird workspace whose wallet has funds, and a phone number you control. The examples use JavaScript on Node.js.

## Prepare your Bird workspace

1. Enable each country your users are in under [**SMS** > **Destinations**](https://bird.com/dashboard/w/sms/destinations). Bird sends SMS only to the countries enabled for your workspace, and rejects a send to any other country.
2. On the same page, set a daily spend limit for each enabled country. An app that texts codes is open to the public, and the limit stops new messages to a country once the day's spend there reaches it. [What is SMS pumping, and how do I stop it?](/explained/sms/what-is-sms-pumping) explains the attack.
3. Open **Platform tools** > [**API keys**](https://bird.com/dashboard/w/api-keys) and create a key with the `sms:write` scope and no other scope. Copy the key: it is shown once.

The [Bird CLI](/docs/cli) does the same from a terminal. Sign in once with the scopes the next two commands need. The second command enables the United States with a limit of 25 USD a day, in a workspace whose wallet is in USD:

```bash
bird auth login --scope sms_management:write --scope api_keys:write --scope sms:write
bird sms destinations update --destination "US=true;25USD"
bird api-keys create --name "Replit app" --scope sms:write
```

The sign-in asks for `sms:write` as well, because the CLI can put on a key only the scopes its own sign-in holds.

## Store the key in Replit Secrets

Store the key as a secret named `BIRD_API_KEY`. Replit encrypts secrets and gives them to your project's code as environment variables.

1. Open your project in the Project Editor and select **Tools**.
2. Under **Setup**, select **Secrets**, and then **New Secret**.
3. Enter `BIRD_API_KEY` as the key and your Bird API key as the value, and select **Add Secret**.

Agent also asks for the key when a change needs it. Add the key in the Secrets tool, not in the chat and not in a file in the project.

Three things about Replit Secrets affect how you use the key:

- **Collaborators can read it.** A collaborator on the project can see secret values, and any code in the project can print them. Create a key for this app alone, with only the `sms:write` scope, so you can revoke it without affecting anything else.
- **Your published app has its own list.** Before you publish, open **Publishing**, select **Adjust settings**, and check that `BIRD_API_KEY` is among the **Production app secrets**.
- **A Static Deployment has no secrets.** A static site has no server code to hold the key. Publish with a deployment type that runs your server.

## Add the send function

Add the [function code](#function-code) to a file in your server code, such as `bird-sms.js`. To have Agent do it, paste this prompt, followed by the function code:

```text
Add server code that sends an SMS verification code through the Bird SMS API.
Use the sendVerificationCode function below without changes, and read the API key
from the BIRD_API_KEY secret. Require a signed-in user for every step.
- Generate a 6-digit code on the server. Store only a hash of it, together with
  the user, the phone number it was sent to, and a 10-minute expiry.
- A new request replaces the stored code. Allow one request per user each minute,
  and five requests per phone number each hour, counted across all users.
- Add a second endpoint that checks the code a user enters, for the
  same user and the same phone number. Delete the stored code when it matches,
  and after five wrong attempts.
```

### Function code

<!-- app-builder:send-verification-code -->

```javascript
// Sends one verification code by SMS with a built-in Bird template. Server-side code only.
export async function sendVerificationCode({
  apiKey,
  to,
  code,
  idempotencyKey = crypto.randomUUID(),
}) {
  const key = /^bk_([a-z]{2}\d+)_[A-Za-z0-9_-]+$/.exec(String(apiKey ?? "").trim());
  if (!key) throw new Error("BIRD_API_KEY is missing or is not a complete bk_ key.");
  if (typeof to !== "string" || !/^\+[1-9]\d{1,14}$/.test(to)) {
    throw new Error("The phone number must be in E.164 format, such as +12025550123.");
  }
  if (typeof code !== "string" || !/^\d{4,8}$/.test(code)) {
    throw new Error("The code must be a string of 4 to 8 digits.");
  }

  const response = await fetch(`https://${key[1]}.platform.bird.com/v1/sms/messages`, {
    method: "POST",
    redirect: "error",
    headers: {
      Authorization: `Bearer ${key[0]}`,
      "Content-Type": "application/json",
      "Idempotency-Key": idempotencyKey,
    },
    body: JSON.stringify({
      to,
      template: { slug: "bird_otp_verification", parameters: { code } },
    }),
    signal: AbortSignal.timeout(10000),
  });
  if (response.status !== 202) {
    // Bird error bodies can echo the recipient, so only the error name leaves this function.
    const name = (await response.json().catch(() => null))?.error?.name;
    const detail = typeof name === "string" && /^[A-Za-z0-9]+$/.test(name) ? ` ${name}` : "";
    throw new Error(`Bird returned HTTP ${response.status}${detail}.`);
  }
  const message = await response.json();
  return { id: message.id, status: message.status };
}
```

<!-- /app-builder:send-verification-code -->

Call the function from your server code with the key from the environment:

<!-- app-builder:send-verification-code-call -->

```javascript
const message = await sendVerificationCode({
  apiKey: process.env.BIRD_API_KEY,
  to: "+12025550123",
  code: "493021",
});
console.log(message.id, message.status);
```

<!-- /app-builder:send-verification-code-call -->

The function does four things:

- **Selects the API region from the key.** A `bk_us1_` key sends through `https://us1.platform.bird.com`, and a `bk_eu1_` key through `https://eu1.platform.bird.com`, so the function needs no region setting.
- **Checks the input before it sends.** It refuses a key that is not a complete `bk_` key, a phone number that is not in [E.164](https://en.wikipedia.org/wiki/E.164) format, and a code that is not four to eight digits. None of these reaches Bird.
- **Sends the code with a template.** `bird_otp_verification` renders as **"493021 is your verification code. Do not share it."** with the code you pass. Bird selects a shared sender for the destination, so the request has no `from`.
- **Reports a failure without the message details.** A response other than `202` becomes an error that carries the HTTP status and the Bird error name, such as `SMSDestinationNotEnabled`. The code, the phone number, and the API key stay out of the error.

Each call sends one message. To retry a send that got no answer, pass the same `idempotencyKey` again, and Bird returns the first result without sending twice. See [Idempotency](/docs/guides/idempotency).

Your app creates the code, stores it, and checks what the user enters. [Protect the endpoint](#protect-the-endpoint) lists what that code must do. For Python, Go, and PHP, [Send your first SMS](/docs/get-started/send-your-first-sms) shows the same request with each SDK.

## Protect the endpoint

A published Replit app is on the public internet, so anyone can call an endpoint that it exposes. An endpoint that texts any number on request can be used for SMS pumping, at your cost. Check six things in the code that calls the function:

- Both endpoints require a signed-in user and reject every other request.
- The code is generated on the server. The browser never supplies the code or the message.
- Code requests are limited for each user, and for each phone number across all users. A limit for each user alone lets many accounts text one number.
- The stored code belongs to one user and one phone number, and the check compares both. A code sent to one number cannot verify another.
- The stored code expires, a new request replaces it, and a match deletes it.
- Wrong attempts are limited. After five, the code is deleted and the user requests a new one. Without a limit, a six-digit code can be guessed before it expires.

The destination list and the daily spend limits in your Bird workspace apply as well, whatever the app's code does.

## Test the function

Request a code for a phone number you control, from your app's preview. The text message arrives from a shared sender. Enter the code in your app. Then confirm three things:

- A wrong code fails, and a new request delivers a new code.
- The message appears on the [**Messages**](https://bird.com/dashboard/w/sms/messages) page in Bird with its delivery status. The code is a sensitive template variable, so the stored message content does not show it.
- A request without a signed-in user sends nothing.

Bird's `202` response means the message is accepted for delivery. It does not prove the phone received it, so check the message status when a user reports a missing code.

## Troubleshoot delivery

| Error from the function                                 | What to check                                                                                                                              |
| ------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| BIRD_API_KEY is missing or is not a complete bk_ key    | The `BIRD_API_KEY` secret exists, holds a complete key that starts with `bk_`, and is among the production app secrets of a published app. |
| Bird returned HTTP 401                                  | The API key is expired or revoked. Create a new key and replace the secret.                                                                |
| Bird returned HTTP 402                                  | The wallet cannot cover the message. Add funds: see [Payment methods and wallet](/docs/knowledge-base/billing/payment-methods-wallet).     |
| Bird returned HTTP 403                                  | The key lacks the `sms` scope at `write` level.                                                                                            |
| Bird returned HTTP 422 SMSDestinationNotEnabled         | The recipient's country is not enabled. Enable it under **SMS** > **Destinations**.                                                        |
| Bird returned HTTP 422 SMSDestinationDailySpendExceeded | The country reached its daily spend limit. Bird refuses new messages to that country until midnight UTC.                                   |
| Bird returned HTTP 429                                  | Your organization reached its SMS send limit. Wait before you retry: see [Rate limits](/docs/guides/rate-limits#when-you-hit-a-limit).     |

## Next steps

- [Sending SMS](/docs/guides/sms/sending-sms): free-text messages with your own sender, destinations, daily spend limits, and message status.
- [SMS templates](/docs/guides/sms/templates): the built-in templates, their variables, and their languages.
- [Authentication & API keys](/docs/guides/authentication): scope, rotate, and revoke the key your app holds.
- [Webhooks & events](/docs/guides/webhooks): receive the delivery result in your app.

## Related resources

- [SMS pumping explained](/learn/sms/sms-pumping-explained) (video)
- [SMS pumping protection](/sms-api) (product)
- [Operate messaging reliably](/learn/paths/reliability) (course)
- [SMS overview](/docs/guides/sms/overview) (docs)

[Get an implementation brief](/learn/workspace?topic=sms-pumping)
