To send an SMS from SvelteKit, call the REST API from a server-only module, then use it in a form action (for your own pages) or a +server.ts endpoint (for everything else). The API key stays in $env/dynamic/private, so it never reaches the browser bundle.

We make Ready, so the code uses the Ready API and only the request shape we document. SvelteKit has one neat trick for texting: your load function can hand the page a fresh idempotency key, so a double click or a refresh-and-resubmit can't send the same text twice.

Keep the call in $lib/server

Anything under src/lib/server can't be imported by client code, and SvelteKit fails the build if you try. That makes it the right home for the key and the fetch.

import { env } from '$env/dynamic/private';

export type SmsResult =
  | { ok: true }
  | { ok: false; status: number };

export async function sendSms(to: string, body: string, key: string): Promise<SmsResult> {
  let status = 0;

  for (let attempt = 0; attempt < 3; attempt++) {
    try {
      const res = await fetch('https://api.tryready.com/v1/messages', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-API-Key': env.READY_API_KEY,
          'Idempotency-Key': key,
        },
        body: JSON.stringify({ to, body, consent_attested: true }),
        signal: AbortSignal.timeout(10_000),
      });
      if (res.ok) return { ok: true };
      status = res.status;
      if (status !== 429 && status < 500) return { ok: false, status };
    } catch {
      status = 0;
    }
    await new Promise((r) => setTimeout(r, 500 * 2 ** attempt));
  }

  return { ok: false, status };
}

The loop retries a 429, any 5xx and network failures, always with the same key. Any other 4xx returns at once, because sending it again won't change the answer. Set consent_attested to true only when the recipient agreed to texts.

We use $env/dynamic/private so the value is read at runtime. If you'd rather fail the build when the variable is missing, $env/static/private does that.

A form action with a key from load

import { fail } from '@sveltejs/kit';
import type { Actions, PageServerLoad } from './$types';
import { sendSms } from '$lib/server/sms';

export const load: PageServerLoad = async () => ({ key: crypto.randomUUID() });

export const actions: Actions = {
  default: async ({ request }) => {
    const form = await request.formData();
    const to = String(form.get('to') ?? '').trim();
    const body = String(form.get('body') ?? '').trim();
    const key = String(form.get('key') ?? '');

    if (!/^\+[1-9]\d{7,14}$/.test(to) || !body || !key) {
      return fail(400, { to, body, error: 'Enter a number like +12125550199 and a message.' });
    }

    const result = await sendSms(to, body, key);
    if (result.ok) return { sent: true };

    const error =
      result.status === 409
        ? "That text can't go out at this hour. Try again later."
        : result.status >= 400 && result.status < 500
          ? "We couldn't send that text. Check the number."
          : 'The texting service is busy. Try again in a minute.';
    return fail(result.status === 409 ? 409 : 502, { to, body, error });
  },
};

The page gets a new UUID on every load. It rides along in a hidden input, so submitting the same form twice sends the same Idempotency-Key and the second request doesn't produce a second text. After a successful action, SvelteKit reruns load, which hands the page a fresh key for the next message.

The page

<script lang="ts">
  import { enhance } from '$app/forms';
  let { data, form } = $props();
  let sending = $state(false);
</script>

<form
  method="POST"
  use:enhance={() => {
    sending = true;
    return async ({ update }) => {
      await update();
      sending = false;
    };
  }}
>
  <input type="hidden" name="key" value={data.key} />
  <input name="to" value={form?.to ?? ''} placeholder="+12125550199" required />
  <textarea name="body" required>{form?.body ?? ''}</textarea>
  <button disabled={sending}>Send text</button>
  {#if form?.error}<p role="alert">{form.error}</p>{/if}
  {#if form?.sent}<p>Text accepted.</p>{/if}
</form>

The form works without JavaScript, and use:enhance upgrades it to a fetch with no page reload. A 409 here is a time rule: the recipient's local quiet hours are in effect, nothing was sent, and the same text can go out once the window opens.

A +server.ts endpoint for other callers

When a mobile app, a webhook or another service needs to trigger a text, expose an endpoint instead:

import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { sendSms } from '$lib/server/sms';

export const POST: RequestHandler = async ({ request }) => {
  const { to, body } = await request.json();
  const key = request.headers.get('idempotency-key') ?? crypto.randomUUID();

  const result = await sendSms(to, body, key);
  if (!result.ok) error(result.status === 409 ? 409 : 502, 'not sent');
  return json({ sent: true });
};

Lock this route down with your own auth in hooks.server.ts before it ships. An open endpoint that texts anyone is an expensive mistake.

Which one to use

NeedUse
A form on your own pageForm action
A caller outside the page (mobile app, another service)+server.ts
Must survive a restart, or many texts at onceA queue, with the same module in the worker
Reply handlingA separate +server.ts that checks the signature and returns 200 fast

Form actions and endpoints run inside the request, so a deploy or a long retry can cut them off. For anything that must arrive, hand the job to a worker; our BullMQ worker guide shows the pattern.

FAQ

Does this work on Vercel or Cloudflare adapters?

Yes. The module uses only fetch, AbortSignal and crypto.randomUUID(), which every adapter runtime has. On Cloudflare, read the key from the platform env instead of process.env; $env/dynamic/private handles that for you.

Where should the idempotency key come from?

Generate it once per message and reuse it on every retry. Here load does it per form view. For a queue, create it when you enqueue. See idempotency and duplicate texts for the rules.

How do I handle replies?

Add a +server.ts route, verify the signature on the raw body, return 200 quickly, dedupe and enqueue the work. Our inbound webhook guide explains why, and the webhook docs on docs.tryready.com cover the details.

The short version

Keep the call in $lib/server, send a load-generated key through the form, and map a 409 to a plain message about timing. The messages API docs list every field, and you can sign up to get a key.