Sign inGet Started

Send Supabase Auth SMS codes with Bird

Use Supabase's Send SMS Hook to deliver the phone sign-in codes of Supabase Auth through Bird. Supabase generates each code and checks what the user enters. The hook is an Edge Function that receives the code and sends it with a built-in Bird SMS template. The template supplies the message text and a shared sender, so you need no sender ID and no sender registration.

Supabase also lists a built-in MessageBird provider. That provider calls the MessageBird API at rest.messagebird.com with a MessageBird access key, and it does not work with a bird.com account. Coming from MessageBird explains how the two accounts differ. Use the hook in this guide with a bird.com account.

Before you start

You need a Supabase project with phone sign-in enabled, the Supabase CLI linked to that project, a Bird workspace whose wallet has funds, and a phone number you control. Set this up in a development project before you change production sign-in.

Prepare your Bird workspace

  1. Enable each country your users sign in from under SMS > Destinations. Bird rejects a send to a country that is not enabled.
  2. On the same page, set a daily spend limit for each enabled country. A sign-in form is open to the public, and the limit stops new codes 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. 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:

Esempio di codice
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 "Supabase Auth" --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.

Create the hook function

  1. Create the function in your Supabase project folder:

    Esempio di codice
    supabase functions new send-sms
  2. Replace the contents of supabase/functions/send-sms/index.ts with the function code.

  3. Supabase calls a hook before a user has a session, so turn off JWT verification for this function in supabase/config.toml. The function verifies Supabase's signature instead:

    Esempio di codice
    [functions.send-sms]
    verify_jwt = false
  4. Deploy the function:

    Esempio di codice
    supabase functions deploy send-sms

    The function runs at https://YOUR_PROJECT_ID.supabase.co/functions/v1/send-sms.

Function code

Esempio di codice
import { Webhook } from "https://esm.sh/standardwebhooks@1.0.0";

const json = (status = 200, body = {}, headers = {}) =>
  new Response(JSON.stringify(body), {
    status,
    headers: { "Content-Type": "application/json", ...headers },
  });

// Supabase Auth does not pass a failed hook's message on, so the function logs it.
const failure = (status = 500, message = "") => {
  console.error(message);
  return json(
    status,
    { error: { http_code: status, message } },
    status === 503 ? { "retry-after": "true" } : {},
  );
};

const hmacHex = async (secret = "", text = "") => {
  const encoder = new TextEncoder();
  const key = await crypto.subtle.importKey(
    "raw",
    encoder.encode(secret),
    { name: "HMAC", hash: "SHA-256" },
    false,
    ["sign"],
  );
  const mac = await crypto.subtle.sign("HMAC", key, encoder.encode(text));
  return Array.from(new Uint8Array(mac), (byte) => byte.toString(16).padStart(2, "0")).join("");
};

const wait = (ms = 0) => new Promise((resolve) => setTimeout(resolve, ms));

Deno.serve(async (req) => {
  const apiKey = (Deno.env.get("BIRD_API_KEY") ?? "").trim();
  const secret = (Deno.env.get("SEND_SMS_HOOK_SECRETS") ?? "").trim().replace("v1,whsec_", "");
  const region = /^bk_([a-z]{2}\d+)_[A-Za-z0-9_-]+$/.exec(apiKey);
  if (!region || !secret) {
    return failure(500, "Set BIRD_API_KEY and SEND_SMS_HOOK_SECRETS for this function.");
  }

  const payload = await req.text();
  let event;
  try {
    event = new Webhook(secret).verify(payload, Object.fromEntries(req.headers));
  } catch {
    return failure(401, "The hook signature is not valid.");
  }
  // sms.phone is the number this code is for, which differs from user.phone during a phone change.
  const phone = String(event?.sms?.phone ?? event?.user?.phone ?? "").replace(/^\+/, "");
  const code = String(event?.sms?.otp ?? "");
  if (!/^[1-9]\d{1,14}$/.test(phone) || !/^\d{4,8}$/.test(code)) {
    return failure(400, "The hook payload needs a phone number and a code of 4 to 8 digits.");
  }

  const request = {
    method: "POST",
    redirect: "error",
    headers: {
      Authorization: `Bearer ${apiKey}`,
      "Content-Type": "application/json",
      // Supabase signs every retry with a new webhook-id, so the key comes from the payload.
      "Idempotency-Key": `supabase-otp/${await hmacHex(secret, payload)}`,
    },
    body: JSON.stringify({
      to: `+${phone}`,
      template: { slug: "bird_otp_verification", parameters: { code } },
    }),
  };
  // Supabase allows five seconds for the hook, its own retries included.
  const deadline = Date.now() + 4500;
  let status = 0;
  for (let attempt = 0; attempt < 4 && Date.now() < deadline; attempt++) {
    if (attempt > 0) await wait(Math.min(400, deadline - Date.now()));
    try {
      const response = await fetch(`https://${region[1]}.platform.bird.com/v1/sms/messages`, {
        ...request,
        signal: AbortSignal.timeout(Math.max(1, Math.min(2000, deadline - Date.now()))),
      });
      // Bird error bodies can echo the recipient. Keep them out of Supabase logs.
      await response.body?.cancel();
      status = response.status;
    } catch {
      status = 0;
    }
    if (status === 202) return json();
    // No answer, or 409 while the first request with this key is still running: ask again.
    if (status !== 0 && status !== 409) break;
  }
  if (status === 0 || status === 409) {
    return failure(503, "Bird did not confirm the message in time. It may still be sent.");
  }
  return failure(status >= 500 ? 503 : 500, `Bird returned HTTP ${status}.`);
});

The function does six things:

  • Verifies the request. Supabase signs each hook call to the Standard Webhooks specification. A request without a valid signature gets 401 and sends nothing.
  • Sends to the number the code is for. Current versions of Supabase Auth put that number in sms.phone. During a phone change it is the new number, while user.phone is still the old one. The function falls back to user.phone when sms.phone is absent, and adds the leading plus sign that Supabase leaves out.
  • Sends the code with a template. bird_otp_verification renders as "493021 is your verification code. Do not share it." with the code Supabase generated. The template accepts a code of four to eight digits, and Supabase's default is six. Supabase's own SMS message text is not used.
  • Makes a retry safe. The Idempotency-Key is derived from the hook payload, so a repeated request with the same code returns the first result and Bird sends one message. A new sign-in request carries a new code and sends normally. See Idempotency.
  • Stays inside Supabase's time limit. Supabase allows five seconds for a hook call, its own retries included, so the function stops after 4.5 seconds. Each request to Bird gets up to two seconds. If a request gets no answer, or Bird answers 409 because the first request is still running, the function asks again with the same key until Bird confirms or the time runs out.
  • Logs why it failed. Supabase Auth reports a failed hook to your application as an error of its own and does not pass the function's message on. The function writes each message to its log, without the code, the phone number, or the API key.

Connect the hook in Supabase

  1. In the Supabase dashboard, open Authentication > Hooks and add the Send SMS hook.

  2. Choose the HTTP type and enter the function URL from the previous section.

  3. Create the hook's secret and copy it. It has the form v1,whsec_ followed by a base64 string.

  4. Store the secret and your Bird API key as function secrets, replacing both example values:

    Esempio di codice
    supabase secrets set SEND_SMS_HOOK_SECRETS="v1,whsec_..." BIRD_API_KEY="bk_us1_..."

Once the hook is enabled, it replaces Supabase's built-in SMS sending, so the SMS provider selected in Supabase's phone settings is no longer used.

The key's prefix selects the API region, so the function needs no region setting: a bk_eu1_ key sends through https://eu1.platform.bird.com.

Test sign-in

Request a code for a phone number you control, from your application or with the Supabase client:

Esempio di codice
const { error } = await supabase.auth.signInWithOtp({ phone: "+12025550123" });

The text message arrives from a shared sender. Enter the code in your application to complete the sign-in. 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.
  • The Edge Function logs in Supabase show no error for the request.

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

Message in the function logsWhat to check
Set BIRD_API_KEY and SEND_SMS_HOOK_SECRETS for this functionBoth secrets are set for the function, and BIRD_API_KEY holds a complete key that starts with bk_, with no placeholder left in it.
The hook signature is not validSEND_SMS_HOOK_SECRETS matches the secret shown for the hook in Supabase, including its v1,whsec_ prefix.
The hook payload needs a phone number and a code of 4 to 8 digitsThe SMS OTP length in your Supabase Auth settings is nine or ten digits. Set it to eight or fewer.
Bird returned HTTP 401The API key is expired or revoked. Create a new key and set it again.
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 422Bird refused the message. The usual causes are a recipient country that is not enabled and a daily spend limit that is reached. Check SMS > Destinations.
Bird returned HTTP 429Your organization reached its SMS send limit. The function reports it without a retry, because a retry would come before the limit resets. See Rate limits.
Bird returned HTTP 500, or a higher statusBird had a server error. The function answers 503, and Supabase calls the hook again at once, up to three times in all. The idempotency key keeps a retry from sending twice.
Bird did not confirm the message in time. It may still be sent.Bird took longer than the hook's time limit. Read the message on the Messages page. Supabase stores a code only when the hook succeeds, so a code that still arrives is not accepted. The user requests a new one.
No message, and no function call for a sign-inThe hook is enabled under Authentication > Hooks and points to the deployed function URL.

Your application sees an error from Supabase Auth for each of these, without the function's message. Read the function's logs in Supabase to tell them apart.

Next steps

Continua con la documentazione, le guide e gli esempi per questo argomento.