To send an SMS from a Vercel function, call the REST API with fetch inside a route handler, set maxDuration so a slow carrier answer doesn't kill the function, and use waitUntil for work that can finish after you've responded. For Vercel Cron, assume the same run can arrive twice, and store one Idempotency-Key on each message row before the first attempt.
We make Ready, so the code uses the Ready REST API and only the request shape we document. If you want the general Next.js setup first, see our Next.js SMS guide. This post is about the platform's own limits: timeouts, background work and cron.
The send helper
Both the route handler and the cron job call the same function, so write it once:
// lib/sms.ts
export type SendResult = { status: number; text: string };
export async function sendSms(to: string, body: string, key: string): Promise<SendResult> {
const apiKey = process.env.READY_API_KEY;
if (!apiKey) throw new Error("READY_API_KEY is not set");
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),
});
return { status: res.status, text: await res.text() };
} Set READY_API_KEY in the project's environment variables, not in the repository. to is E.164. Set consent_attested to true only when the recipient agreed to texts, and pass the real answer from your own consent data in production code.
The AbortSignal.timeout matters on a serverless platform. A function that waits on a stalled socket is billed for the wait and then killed at its limit, with no chance to log what happened. Ten seconds for the HTTP call, inside a larger function budget, keeps the failure in your hands.
The function budget
Vercel functions have a maximum duration that depends on your plan and runtime settings, and the numbers change, so check Vercel's current limits rather than trusting a blog post. What you control is the setting. In a Next.js App Router handler:
// app/api/orders/[id]/shipped/route.ts
import { waitUntil } from "@vercel/functions";
import { sendSms } from "@/lib/sms";
export const maxDuration = 30;
export async function POST(req: Request, { params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
const key = req.headers.get("idempotency-key") ?? crypto.randomUUID();
waitUntil(
sendSms("+12125550199", `Your order #${id} has shipped.`, key).then(({ status, text }) => {
if (status >= 400) console.error("sms not sent", status, text);
}),
);
return Response.json({ accepted: true }, { status: 202 });
} waitUntil tells the platform to keep the function alive after the response is returned, so the user isn't waiting on a carrier. It's a good fit for work that is nice to finish, such as a receipt text.
It isn't a queue. If the function is cut off, or the call fails, nothing retries it. Choose by what a lost text costs:
| Situation | Pattern | Why |
|---|---|---|
| User is waiting on the result | Await the send in the handler | The caller needs the answer |
| A lost text is a minor loss | waitUntil | Fast response, no extra infrastructure |
| The text must arrive | Store a row, send from cron or a queue | A retry has somewhere to read from |
For the middle case, log failures with the key so a person can resend. For the last case, keep reading.
Retries without a queue
A handler can retry briefly inside one invocation, as long as the key stays the same. Add this beside sendSms in lib/sms.ts:
export async function sendWithRetry(to: string, body: string, key: string) {
for (let attempt = 0; attempt < 4; attempt++) {
const r = await sendSms(to, body, key);
const retry =
r.status === 429 ||
(r.status >= 500 && r.status !== 503) ||
(r.status === 409 && r.text.includes("idempotency_in_progress"));
if (!retry) return r;
await new Promise((ok) => setTimeout(ok, 500 * 2 ** attempt + Math.random() * 250));
}
return { status: 599, text: "gave up" };
} A repeated key means the request isn't sent twice, which is what makes a retry after a timeout safe. A 503 means the message was not sent, so resend it with a new key. A 409 QUIET_HOURS_BLOCK is a time rule: an API text is held only if the window opens within a few hours, so otherwise you send it again once the window opens. Keep the total backoff well under maxDuration. Our retries guide has the full status table.
Vercel Cron
Cron jobs are declared in vercel.json and call a path on your deployment:
{
"crons": [
{ "path": "/api/cron/send-reminders", "schedule": "*/15 * * * *" }
]
} Vercel calls the path with a GET request. Schedules are in UTC, and what you can run depends on your plan, so check the current cron limits. Secure the route by setting a CRON_SECRET environment variable: Vercel then sends it as a bearer token, and you reject anything else.
// app/api/cron/send-reminders/route.ts
import { sendWithRetry } from "@/lib/sms";
import { claimDueReminders, markSent, markFailed } from "@/lib/reminders";
export const maxDuration = 60;
export async function GET(req: Request) {
if (req.headers.get("authorization") !== `Bearer ${process.env.CRON_SECRET}`) {
return new Response("Unauthorized", { status: 401 });
}
for (const r of await claimDueReminders(25)) {
const res = await sendWithRetry(r.phone, r.text, r.idempotencyKey);
if (res.status >= 200 && res.status < 300) await markSent(r.id);
else await markFailed(r.id, res.status);
}
return Response.json({ ok: true });
} claimDueReminders, markSent and markFailed are your own database code, shown here as placeholders. The important part is r.idempotencyKey: a UUID created when the reminder row was inserted, never when the cron ran.
Why the key lives on the row
Cron delivery isn't guaranteed to be exactly once. Vercel's own docs say the same event can occasionally be delivered more than once, and a run that times out halfway leaves some rows sent and some not. If each row owns its key, a second run that reaches an already-sent row sends the same key again, and the API treats it as a repeat. If you generated a fresh UUID per run, the customer would get two texts.
Process a small batch per run (25 above), and let the next run pick up the rest. A batch that fits comfortably inside maxDuration beats one that gets cut off at row 80. For more cron patterns outside Vercel, see our GitHub Actions and cron guide.
Receiving replies
Inbound texts and delivery updates arrive as webhooks. See the webhook docs for the payload. In a function, verify the signature against the raw body, return 200 fast, dedupe, and enqueue the real work. Our fast-ack serverless webhook guide covers it.
FAQ
Is waitUntil enough for important texts?
No. It extends the function's life but doesn't retry. For a text that must arrive, persist the message and its key first, then send.
Does a Vercel Cron run in preview deployments?
Cron jobs run on production deployments only, so test the route by calling it yourself with the bearer token.
Where should the idempotency key come from?
From the thing the text is about: the reminder row, the order, the booking. One message, one key, created before the first attempt. Our idempotency guide goes deeper.
The short version
Await when someone's waiting, waitUntil when a miss is cheap, and a stored row with its own key when the text must arrive. The messages API docs list every field, and you can sign up for a key.