Sign inGet Started

Send SMS from a Lovable app with Bird

Send SMS from an app you build in Lovable by calling the Bird SMS API from the app's server-side 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.

Lovable has no built-in Bird connector. Two connections exist, and they do different jobs:

  • While you build: add Bird's MCP server as a chat connector, so Lovable can read and configure your Bird workspace from the project chat. Bird for Lovable shows that setup.
  • While your app runs: your app calls the Bird API with an API key held in the project's 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 these cases:

  • 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.
  • Your users sign in with their phone number, and your project is connected to your own Supabase project. Supabase creates and checks the code. Deliver it through Bird with the Supabase Auth guide, and skip the rest of this guide.
  • You plan to select MessageBird in Lovable's phone sign-in settings. That option does not work with a bird.com account. See Use Bird for phone sign-in.

Stay with this guide when your app keeps its own codes, for example to verify the phone number of a user who is already signed in. 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 Lovable project, a Bird workspace whose wallet has funds, and a phone number you control.

Prepare your Bird workspace

  1. 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.
  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? explains the attack.
  3. Open Platform tools > 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 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:

Code example
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 "Lovable 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 Lovable

Store the key as a project secret named BIRD_API_KEY. Lovable injects project secrets into the app's server-side code and does not send them to the browser.

  1. In your Lovable project, open More > Settings > Secrets and select Add secret.
  2. Enter BIRD_API_KEY as the name and your key as the value.

Lovable also opens this form when a change needs a secret. Enter the key in the form, not in the project chat, so the key stays out of the chat history.

Do not put the key in the .env file or in a variable whose name starts with VITE_. Lovable builds those values into the code that runs in the browser, where anyone can read them.

If your project is connected to your own Supabase project, Lovable shows a Manage secrets button that opens the Supabase dashboard. Add BIRD_API_KEY there.

Add the send function

Ask Lovable in the project chat to add the function. Paste this prompt, followed by the function code:

Code example
Add server-side 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 server-side function 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.

Lovable writes a server function in newer projects, and an Edge Function in the built-in backend of older ones. The function below uses fetch and other standard web APIs, and no package, so it does not depend on which of the two your project has.

Lovable also writes the code that reads the secret and passes it to the function as apiKey. Lovable's documentation shows how an Edge Function reads a secret: Deno.env.get("BIRD_API_KEY"). It does not show the expression for a server function, so this guide does not name one. In a server function, ask Lovable in the project chat to show the line that reads BIRD_API_KEY, and check that the line is in server-side code.

Function code

Code example
// 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 };
}

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 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.

Your app creates the code, stores it, and checks what the user enters. Protect the function lists what that code must do.

Protect the function

Anyone who knows the address of a server function or an Edge Function can send it a request. A function that texts any number on request can be used for SMS pumping, at your cost. Check six things in the code Lovable wrote:

  • Both functions 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.

Use Bird for phone sign-in

Lovable's phone sign-in settings list MessageBird as an SMS provider, with an access key and an originator. Lovable's built-in backend uses Supabase's open-source foundation, and Supabase Auth's MessageBird provider calls the MessageBird API at rest.messagebird.com with a MessageBird access key. It does not work with a bird.com account, so do not enter a bk_ key there. Coming from MessageBird explains how the two accounts differ.

With a bird.com account, choose by how your project is set up:

  • Your project is connected to your own Supabase project. Supabase manages sign-in. Deliver its phone sign-in codes through Bird with the Supabase Auth guide, which uses Supabase's Send SMS Hook.
  • Your project uses Lovable's built-in backend. Sign users in with another method, such as email, and verify the phone number afterwards with the function in this guide or with Verify.

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 functionWhat to check
BIRD_API_KEY is missing or is not a complete bk_ keyThe BIRD_API_KEY secret exists in the project and holds a complete key that starts with bk_. A MessageBird access key does not work.
Bird returned HTTP 401The API key is expired or revoked. Create a new key and replace the secret.
Bird returned HTTP 402The wallet cannot cover the message. Add funds: see Payment methods and wallet.
Bird returned HTTP 403The key lacks the sms scope at write level.
Bird returned HTTP 422 SMSDestinationNotEnabledThe recipient's country is not enabled. Enable it under SMS > Destinations.
Bird returned HTTP 422 SMSDestinationDailySpendExceededThe country reached its daily spend limit. Bird refuses new messages to that country until midnight UTC.
Bird returned HTTP 429Your organization reached its SMS send limit. Wait before you retry: see Rate limits.
The function is not called, or the key is undefinedThe code that calls Bird runs on the server, and the secret's name is exactly BIRD_API_KEY. Ask Lovable to show where the function reads the secret.

Next steps

Continue with the documentation, guides and examples for this topic.