Send SMS from a Replit app with Bird
Send SMS from an app you build on Replit 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 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 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
- Enable each country your users are in under SMS > Destinations. Bird sends SMS only to the countries enabled for your workspace, and rejects a send to any other country.
- 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? explains the attack.
- Open Platform tools > API keys and create a key with the
sms:writescope and no other scope. Copy the key: it is shown once.
The Bird 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:
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:writeThe 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.
- Open your project in the Project Editor and select Tools.
- Under Setup, select Secrets, and then New Secret.
- Enter
BIRD_API_KEYas 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:writescope, 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_KEYis 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 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:
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
// 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 };
}Call the function from your server code with the key from the environment:
const message = await sendVerificationCode({
apiKey: process.env.BIRD_API_KEY,
to: "+12025550123",
code: "493021",
});
console.log(message.id, message.status);The function does four things:
- Selects the API region from the key. A
bk_us1_key sends throughhttps://us1.platform.bird.com, and abk_eu1_key throughhttps://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 format, and a code that is not four to eight digits. None of these reaches Bird. - Sends the code with a template.
bird_otp_verificationrenders 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 nofrom. - Reports a failure without the message details. A response other than
202becomes an error that carries the HTTP status and the Bird error name, such asSMSDestinationNotEnabled. 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.
Your app creates the code, stores it, and checks what the user enters. Protect the endpoint lists what that code must do. For Python, Go, and PHP, 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 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. |
| 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. |
Next steps
- Sending SMS: free-text messages with your own sender, destinations, daily spend limits, and message status.
- SMS templates: the built-in templates, their variables, and their languages.
- Authentication & API keys: scope, rotate, and revoke the key your app holds.
- Webhooks & events: receive the delivery result in your app.