To send an SMS from Firebase Cloud Functions, call POST /v1/messages with fetch from inside the function, keep the API key in a function secret, and send an Idempotency-Key header built once per message. The idempotency part is the one that matters on Firebase, because Firestore triggers can run more than once for the same document.

The usual pattern is simple: a document is written (an order, an appointment, a signup), a trigger fires, and the function texts the customer. This post shows that function in full, how to set up the secret, and how to make the send safe when the platform retries.

A Firestore trigger that sends a text

This uses a second-generation function with the Node runtime, which has fetch built in. The trigger fires when a document is created in an appointments collection and texts the customer a reminder. Collection and field names are examples; use your own.

const { onDocumentCreated } = require("firebase-functions/v2/firestore");
const { defineSecret } = require("firebase-functions/params");

const readyKey = defineSecret("READY_API_KEY");

exports.textAppointment = onDocumentCreated(
  { document: "appointments/{id}", secrets: [readyKey], retry: true },
  async (event) => {
    const data = event.data.data();
    if (!data.phone || data.textSentAt) return;

    const res = await fetch("https://api.tryready.com/v1/messages", {
      method: "POST",
      headers: {
        "X-API-Key": readyKey.value(),
        "Content-Type": "application/json",
        "Idempotency-Key": data.textKey,
      },
      body: JSON.stringify({
        to: data.phone,
        body: `Your appointment is confirmed for ${data.when}. Reply STOP to opt out.`,
        consent_attested: true,
      }),
      signal: AbortSignal.timeout(8000),
    });

    if (res.status === 429 || res.status >= 500) {
      throw new Error(`Ready returned ${res.status}`);
    }
    if (!res.ok) {
      console.error("send refused", res.status, event.params.id, await res.text());
      return;
    }
    await event.data.ref.update({ textSentAt: new Date() });
  }
);

A few choices in that function are deliberate.

  • to is E.164. A 10-digit US number is treated as +1, but store numbers in E.164 so there's no guessing.
  • consent_attested: true is your statement that the recipient agreed to texts. Only set it when that's true for this person.
  • Unless the account turns it off, Ready adds "Reply STOP to opt out" and the business name to the first text to each contact, so you don't have to build the footer yourself. Count those characters if your message sits near a segment limit.

Store the key in a function secret

Don't put the API key in source, in .env files you commit, or in plain function config. Set it with firebase functions:secrets:set READY_API_KEY, which stores it in Google Secret Manager, then list the secret in the function's secrets option as above. Only functions that name the secret can read it, and the value is available at runtime through readyKey.value().

For local work with the emulator, use a local secrets file that stays out of version control, and use a separate key from production. Our post on API key security and rotation covers rotating a key without a gap.

Why retries make idempotency non-negotiable

Cloud Functions give you at-least-once delivery for event triggers. The function can run twice for one document write, and with retry: true it will rerun after an error until it succeeds or the retry window ends. Both are good behavior for reliability and bad news for a text message.

The fix is a stable Idempotency-Key: one UUID per message, reused on every retry. Ready then treats a repeated request as the same send, so the second run doesn't text the customer again.

The important detail is where the key comes from. Generate it once when the document is written (in the client or in the code that creates the appointment) and store it on the document as textKey. If you generate a new UUID inside the trigger, each rerun gets a different key and the protection is gone.

Key sourceSafe on retry?
UUID stored on the document at creationYes
UUID created inside the triggerNo, every run is a new message
Document ID used as the keyOnly if it's a valid UUID and you never send two different texts for one document

If one document can produce several texts (confirmation, reminder, follow-up), store one key per purpose, such as confirmKey and reminderKey. For the longer explanation, see idempotency and duplicate texts.

Retry only what a retry can fix

The function above throws on 429 and 5xx so Firebase reruns it, and returns on other errors so it doesn't loop. A 4xx means the request itself was refused: a malformed number, a missing field, or a number that already opted out. Rerunning won't change that answer, and an endless retry loop on a refused send wastes calls. The error reference lists the codes, and SMS API retries and failure handling goes deeper.

Also set a timeout on the call, as AbortSignal.timeout does here, shorter than the function's own timeout. A slow upstream should fail the attempt cleanly, not kill the function mid-send.

The textSentAt write is a second guard for your own records, not a replacement for the header. It lets you skip documents that already texted and gives you something to query later.

Opt-outs, quiet hours and what Ready handles

You don't need to check opt-outs yourself for a normal send: opted-out numbers and numbers on your Ban list are refused up front and not charged. If you're moving from another tool, check GET /v1/opt-outs/:phone for numbers that opted out there before the first send; the opt-outs docs cover it.

Quiet hours apply to API texts too. If the recipient's window opens within 6 hours, the text is held and sent then. Otherwise it isn't sent and the API answers 409 QUIET_HOURS_BLOCK, so your function should log that and send again after the window opens. These rules reduce risk but don't make a send compliant on their own; consent and message content stay with you.

Cost and registration

A segment costs $0.0075 plus a $0.0045 carrier fee. You need a card on file and a number of your own ($2 a month). An account can send up to 500 texts a month before it registers; after that it has to, and most approvals take 2 to 7 days. Accounts opened before November 12, 2026 keep their signup prices, shown under Billing. See the pricing page. For the same pattern on another serverless platform, see sending SMS from AWS Lambda.

Frequently asked questions

Can Firebase Cloud Functions send SMS without a library?

Yes. Node 18 and later include fetch, and the API is one JSON POST. There's no package to add.

Will a Firestore trigger send the same text twice?

It can run twice, which is why the Idempotency-Key header matters. With the same key on every run, Ready doesn't send a second text.

Where should I keep the API key?

In a function secret backed by Secret Manager, listed in the function's secrets option. Not in source or in a committed config file.

The short version

Trigger on the write, send with fetch, store the key in a secret, create the idempotency key once when the document is written, and retry only on timeouts, 429 and 5xx. The API quickstart gets you a first send, and the messages reference lists the fields. When you want to try it, sign up and send from your own number.