To send an SMS from Remix or React Router v7, write an action that reads the form, calls the REST API from a .server module, and returns either a redirect or an error with the right status. The browser never sees the API key, because .server files are stripped from the client build.
We make Ready, so the code uses the Ready API and only the request shape we document. The examples use React Router v7 imports. In Remix 2, the same code works with @remix-run/node and json in place of data.
A .server module for the call
Any file ending in .server.ts is excluded from the client bundle, and the build errors if client code imports it.
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': process.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 };
} Name it app/sms.server.ts. The loop retries a 429, any 5xx and network failures with the same Idempotency-Key, so a retry after a timeout can't send a second text. Other 4xx answers return at once, since asking again won't change them. Set consent_attested to true only when the recipient agreed to texts.
On Cloudflare, process.env isn't there. Pass the key in from context.cloudflare.env and add it as a fourth argument instead.
The route module
import { data, redirect, Form, useActionData, useLoaderData, useNavigation } from 'react-router';
import type { Route } from './+types/send';
import { sendSms } from '~/sms.server';
export async function loader() {
return { key: crypto.randomUUID() };
}
export async function action({ request }: Route.ActionArgs) {
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 data({ error: 'Enter a number like +12125550199 and a message.' }, { status: 400 });
}
const result = await sendSms(to, body, key);
if (result.ok) return redirect('/send?sent=1');
if (result.status === 409) {
return data({ error: "That text can't go out at this hour. Try again later." }, { status: 409 });
}
if (result.status >= 400 && result.status < 500) {
return data({ error: "We couldn't send that text. Check the number." }, { status: 422 });
}
return data({ error: 'The texting service is busy. Try again in a minute.' }, { status: 502 });
}
export default function Send() {
const { key } = useLoaderData<typeof loader>();
const actionData = useActionData<typeof action>();
const busy = useNavigation().state === 'submitting';
return (
<Form method="post">
<input type="hidden" name="key" value={key} />
<input name="to" placeholder="+12125550199" required />
<textarea name="body" required />
<button disabled={busy}>{busy ? 'Sending' : 'Send text'}</button>
{actionData?.error && <p role="alert">{actionData.error}</p>}
</Form>
);
} The loader mints a UUID, the form posts it back, and the action passes it to Ready. A double click, a back-button resubmit or a retried navigation all carry the same key, so only one text goes out. Redirecting after success follows the post/redirect/get pattern: the loader reruns, a new key appears, and refreshing the page can't resend the old message.
What each answer does
| Ready answered | Meaning | Action returns |
|---|---|---|
| 2xx | Accepted | Redirect |
409 QUIET_HOURS_BLOCK | A time rule: nothing sent, send again once the window opens | data(..., 409) |
| Other 4xx | Bad number, opted-out contact, bad request | data(..., 422) |
| 429 or 5xx after retries | Transient and still failing | data(..., 502) |
Keep the 409 message about timing, not about failure. It isn't a bug, and the user can try again later. The errors docs list every code.
A resource route for other callers
A route module with an action and no default export is a resource route. It answers POST /api/sms with JSON, which suits a mobile app or another service:
import { data } from 'react-router';
import type { Route } from './+types/api.sms';
import { sendSms } from '~/sms.server';
export async function action({ request }: Route.ActionArgs) {
const { to, body } = await request.json();
const key = request.headers.get('idempotency-key') ?? crypto.randomUUID();
const result = await sendSms(to, body, key);
return result.ok ? { sent: true } : data({ error: 'not sent' }, { status: result.status === 409 ? 409 : 502 });
} Authenticate it first, in your session or middleware layer. A route that texts any number for any caller is an abuse risk.
Keep slow work out of the action
Actions run inside the request. They're fine for one text a user is waiting on. For many texts, or anything that must survive a deploy, hand the job to a worker; our BullMQ worker guide shows how. The retries and failure handling guide covers the policy.
FAQ
Can I call the API from a clientAction or a component?
No. Anything that runs in the browser would expose your key. Keep the call in a server action or a resource route.
Does this work on Cloudflare Workers or Vercel?
Yes. The module uses only fetch, AbortSignal and crypto.randomUUID(). Only the way you read the key changes, so pass it in from the platform's environment where process.env isn't available.
How do I handle inbound replies?
Add a resource route that reads the raw body, verifies the signature, returns 200 fast, dedupes and enqueues the work. Our inbound webhook guide explains why, and the webhook docs on docs.tryready.com have the details.
The short version
A .server module for the call, a loader-made key in a hidden field, and an action that maps each answer to a status. The messages API docs list every field, and you can sign up to get a key.