To send an SMS from Netlify, call the REST API with fetch from a function. Use a regular function when the caller needs an answer fast, a background function when the work could outlast the request timeout, and a scheduled function for timed sends. In all three, create the Idempotency-Key before the first attempt and pass it in, so a rerun can't text anyone twice.

We make Ready, so the code uses the Ready REST API and only the request shape we document. For the same idea on another platform, see our guide to sending SMS from serverless functions. This post sticks to what's specific to Netlify.

Pick the function type first

TypeFileUse it forCaller sees
Regular functionnetlify/functions/notify.mtsA form or webhook that needs a quick answerThe real response
Background functionnetlify/functions/send-background.mtsSends with retries that may run longAn immediate 202, no body
Scheduled functionnetlify/functions/reminders.mtsReminders and timed sendsNothing, Netlify runs it

Execution limits differ between the three, and they change, so check Netlify's current numbers. As a rule of thumb, a regular function has a short default timeout (on the order of ten seconds), a scheduled function has a short limit too, and a background function is allowed to run for many minutes. Design for the short limits and treat the long one as a safety margin.

A regular function

// netlify/functions/notify.mts
import type { Config } from "@netlify/functions";

export default async (req: Request) => {
  const { to, body, key } = await req.json();
  const apiKey = Netlify.env.get("READY_API_KEY");
  if (!apiKey) return new Response("READY_API_KEY is not set", { status: 500 });

  const res = await fetch("https://api.tryready.com/v1/messages", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "X-API-Key": apiKey,
      "Idempotency-Key": key ?? crypto.randomUUID(),
    },
    body: JSON.stringify({ to, body, consent_attested: true }),
    signal: AbortSignal.timeout(8_000),
  });

  return new Response(await res.text(), { status: res.status });
};

export const config: Config = { path: "/api/notify" };

Set READY_API_KEY in the site's environment variables in the Netlify UI, not in the repository. to is E.164, and a 10-digit US number is treated as +1. Set consent_attested to true only when the recipient agreed to texts, and take that from your own consent data in real code.

The timeout on the fetch is shorter than the function's own limit on purpose. If the carrier side stalls, you get a clean error you can log, instead of a function killed with no output.

This version makes no retries. If the caller is a browser or a webhook, return the status and let the caller decide, with the same key in the body. A retry from the caller then reuses the same Idempotency-Key.

A background function for retries

Name the file with a -background suffix and Netlify answers the caller with a 202 straight away, then runs your code. That's the place for a retry loop, because nobody is waiting on it.

// netlify/functions/send-background.mts
export default async (req: Request) => {
  const { to, body, key } = await req.json();
  const apiKey = Netlify.env.get("READY_API_KEY")!;

  for (let attempt = 0; attempt < 5; attempt++) {
    const res = await fetch("https://api.tryready.com/v1/messages", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "X-API-Key": apiKey,
        "Idempotency-Key": key,
      },
      body: JSON.stringify({ to, body, consent_attested: true }),
      signal: AbortSignal.timeout(10_000),
    });
    if (res.ok) return;

    const text = await res.text();
    const retry =
      res.status === 429 ||
      (res.status >= 500 && res.status !== 503) ||
      (res.status === 409 && text.includes("idempotency_in_progress"));
    if (!retry) {
      console.error("sms parked", res.status, text);
      return;
    }
    await new Promise((ok) => setTimeout(ok, 1000 * 2 ** attempt));
  }
  console.error("sms gave up", key);
};

The caller creates the key and sends it in the payload. That detail carries the whole design: if the platform runs a background function again after an error, or your caller posts the same payload twice, the same key reaches the API, and a repeated key means the request isn't sent twice.

A background function can't return data to the caller, so log failures with the key, and write the outcome to your own database if a person needs to see it. What to do with each status:

  • 429 and 5xx other than 503: retry with the same key, as above.
  • 503: the message was not sent. Resend with a new key.
  • 409 QUIET_HOURS_BLOCK: a time rule, not a fault. An API text is held only if the window opens within a few hours, so otherwise you send it again once the window opens.
  • Other 4xx: a bad number, an opted-out contact or a validation problem. Log it and stop, because retrying can't fix it.

Our retries and failure handling guide has the whole table.

A scheduled function

Scheduled functions take a cron expression in config. Netlify only runs them on the published production deploy, not on deploy previews, and times are UTC.

// netlify/functions/reminders.mts
import type { Config } from "@netlify/functions";
import { claimDueReminders, markSent, markFailed } from "../lib/reminders";

export default async () => {
  const apiKey = Netlify.env.get("READY_API_KEY")!;

  for (const r of await claimDueReminders(20)) {
    const res = await fetch("https://api.tryready.com/v1/messages", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "X-API-Key": apiKey,
        "Idempotency-Key": r.idempotencyKey,
      },
      body: JSON.stringify({ to: r.phone, body: r.text, consent_attested: true }),
      signal: AbortSignal.timeout(8_000),
    });
    if (res.ok) await markSent(r.id);
    else await markFailed(r.id, res.status);
  }
};

export const config: Config = { schedule: "*/15 * * * *" };

claimDueReminders, markSent and markFailed are placeholders for your own database code. The part to copy is r.idempotencyKey: a UUID stored on the row when the reminder was created. If a run is cut off after sending some rows and the next run reaches them again, the same keys go out and nothing is texted twice.

Keep the batch small enough to finish inside the scheduled limit. A failed row stays in your table with its status, and the next run, or a person, handles it. For cron patterns on other hosts, our GitHub Actions and cron guide compares the options.

Fan out from the scheduled function

If a run has more rows than it can finish, don't extend the loop. Have the scheduled function post each row's payload to the background function and return. Each background invocation then owns one message and its key, and one slow send can't hold up the others.

FAQ

Can a background function return the result to the caller?

No. The caller gets the 202 and nothing more, so record the outcome yourself, keyed by the Idempotency-Key.

Will a scheduled function run in a deploy preview?

No, they run on the published deploy only. Test the logic by importing the handler in a local script or calling it from a regular function.

How do I receive replies?

Inbound texts arrive as webhooks. See the webhook docs for the payload, then verify the signature, return 200 fast, dedupe and enqueue the work. Our fast-ack webhook guide covers the serverless case.

The short version

Regular functions for quick answers, background functions for retries, scheduled functions for timed sends, and one stored key per message in all of them. The messages API docs list every field. To try it, create an account.