To send an SMS from Nuxt 3, add a Nitro route under server/api/, keep the API key in private runtimeConfig, and call the REST API with $fetch. Nitro's $fetch (ofetch) has retries built in, which is safe for a text only when you send an Idempotency-Key.
We make Ready, so the code uses the Ready API and only the request shape we document. Nothing here runs in the browser: a file in server/ never ships to the client, which is exactly where an API key belongs.
Put the key in runtimeConfig
Private keys in runtimeConfig stay on the server. Top-level keys are private; anything under public is exposed to the client.
export default defineNuxtConfig({
runtimeConfig: {
readyApiKey: process.env.READY_API_KEY ?? '',
},
}); Nuxt can also fill readyApiKey from a NUXT_READY_API_KEY variable at runtime, which is handy when the build and the deploy happen in different places. Reading READY_API_KEY as above keeps the name the same as in every other service you run. Don't commit the value; keep it in your host's secret store. Our guide to API key security and rotation covers the rest.
A server utility
Files in server/utils/ are auto-imported into every route, so one helper serves the whole app.
import type { H3Event } from 'h3';
import type { FetchError } from 'ofetch';
export async function sendSms(event: H3Event, to: string, body: string, key: string) {
const { readyApiKey } = useRuntimeConfig(event);
try {
await $fetch('https://api.tryready.com/v1/messages', {
method: 'POST',
headers: { 'X-API-Key': readyApiKey, 'Idempotency-Key': key },
body: { to, body, consent_attested: true },
timeout: 10_000,
retry: 3,
retryDelay: 500,
retryStatusCodes: [429, 500, 502, 503, 504],
});
return { ok: true as const };
} catch (err) {
return { ok: false as const, status: (err as FetchError).statusCode ?? 0 };
}
} A few details are worth knowing. ofetch doesn't retry a POST by default, because a repeated POST can repeat its effect. Setting retry explicitly turns it on, and the Idempotency-Key is what makes that safe: every attempt carries the same key, so Ready treats them as one message. Network errors and timeouts are retried too. A plain object in body is serialized to JSON for you.
Set consent_attested to true only when the recipient agreed to receive texts.
The route
import { z } from 'zod';
const schema = z.object({
to: z.string().regex(/^\+[1-9]\d{7,14}$/),
body: z.string().min(1).max(1600),
});
export default defineEventHandler(async (event) => {
const input = await readValidatedBody(event, schema.parse);
const key = getHeader(event, 'idempotency-key') ?? crypto.randomUUID();
const result = await sendSms(event, input.to, input.body, key);
if (result.ok) return { sent: true, key };
if (result.status === 409) {
throw createError({ statusCode: 409, statusMessage: 'Quiet hours: send again later' });
}
throw createError({
statusCode: result.status >= 400 && result.status < 500 ? 422 : 502,
statusMessage: 'Text not sent',
});
}); Name the file server/api/sms.post.ts and Nitro serves it as POST /api/sms and nothing else. If the validation fails, readValidatedBody throws a 400 on its own.
Call it from a page or component like any other API:
const { data, error } = await useFetch('/api/sms', {
method: 'POST',
headers: { 'Idempotency-Key': crypto.randomUUID() },
body: { to: '+12125550199', body: 'Your order #1042 has shipped.' },
immediate: false,
}); Create the key once per user action, not once per call to your handler. Then a double click, or the browser retrying a dropped request, sends the same key to your route and on to Ready.
Mapping Ready's answers to your own
| Ready answered | What it means | Your route returns |
|---|---|---|
| 2xx | Accepted | 200 |
409 QUIET_HOURS_BLOCK | A time rule: nothing was sent, send again once the window opens | 409 |
| Other 4xx | Bad number, opted-out contact, bad request | 422 |
| 429 or 5xx after retries | Transient and still failing | 502 |
The 409 isn't a fault, so show it as a message about timing rather than an error page. The full list of codes is in the errors docs.
When the request shouldn't wait
Retries inside a request add latency. If a user is waiting on the page, three attempts with half-second backoff is acceptable. If you're texting a few hundred people, don't loop inside a handler. Use a queue, or a Nitro task triggered by a schedule, and let a worker call the same sendSms. Our Node.js guide shows the plain version, and the retries guide shows how to set a policy.
FAQ
Can I call the API from a Vue component?
Don't. Anything in a component can end up in the client bundle, and a browser request would expose your key. Call your own /api/sms route and keep the key on the server.
Does this run on Cloudflare or Vercel Edge?
Yes. Nitro compiles to those presets, and the code uses only $fetch, crypto.randomUUID() and useRuntimeConfig. On Cloudflare, the secret comes from the worker's environment.
How do I receive replies?
Add another route, such as server/api/sms-webhook.post.ts. Read the raw body with readRawBody, verify the signature, return 200 fast, dedupe and enqueue the work. The inbound webhook guide explains the pattern, and the webhook docs on docs.tryready.com give the details.
The short version
Private runtimeConfig for the key, one auto-imported helper, $fetch retries paired with an idempotency key, and a 409 mapped to a timing message. The messages API docs list every field, and you can sign up to get a key.