To send an SMS from Next.js, call your provider's REST API from server code only: a route handler (app/api/.../route.ts) or a server action. Never from a client component. The API key stays in a server environment variable, and the browser never sees it or the provider's URL.

We make Ready, so the example uses the Ready REST API and only the request shape we document. It's written for the App Router and TypeScript, but the same logic works in a Pages Router API route.

The one rule: the key never reaches the browser

Next.js exposes any environment variable prefixed with NEXT_PUBLIC_ to client code. Your SMS key must not have that prefix. Put READY_API_KEY in .env.local for development and in your host's secret store for production, and read it only inside a route handler, server action or server component. If a text-send button needs to exist in the UI, the button calls your server code, and your server code calls the API.

This also protects you from abuse. A public endpoint that texts any number you give it is a free spam relay. Check the session, rate-limit by user, and only text numbers your app already holds.

A route handler

// app/api/notify/route.ts
import { NextResponse } from "next/server";
import { randomUUID } from "node:crypto";

export async function POST(req: Request) {
  const { phone, text, dedupeKey } = await req.json();
  if (typeof phone !== "string" || typeof text !== "string") {
    return NextResponse.json({ error: "bad input" }, { status: 400 });
  }

  const res = await fetch("https://api.tryready.com/v1/messages", {
    method: "POST",
    headers: {
      "X-API-Key": process.env.READY_API_KEY!,
      "Content-Type": "application/json",
      "Idempotency-Key": dedupeKey ?? randomUUID(),
    },
    body: JSON.stringify({ to: phone, body: text, consent_attested: true }),
    signal: AbortSignal.timeout(10000),
  });

  const data = await res.json().catch(() => ({}));
  return NextResponse.json(data, { status: res.status });
}

Add your own authentication check at the top; the example leaves it out to stay short. Passing the provider's status through lets your front end tell a refused send from a server failure. The error body shapes are in the error reference.

A server action

If the text is triggered by a form, a server action avoids the extra endpoint:

"use server";

export async function sendReceipt(orderId: string, phone: string) {
  const res = await fetch("https://api.tryready.com/v1/messages", {
    method: "POST",
    headers: {
      "X-API-Key": process.env.READY_API_KEY!,
      "Content-Type": "application/json",
      "Idempotency-Key": `${orderId}-receipt`,
    },
    body: JSON.stringify({
      to: phone,
      body: `Thanks! Your receipt for order ${orderId} is in your email.`,
      consent_attested: true,
    }),
    signal: AbortSignal.timeout(10000),
    cache: "no-store",
  });
  return { ok: res.ok, status: res.status };
}

Note the idempotency key. A double click on the submit button, a retried request or a user hitting back and resubmitting all produce the same key, so the customer gets one text. Our post on duplicate texts and idempotency covers the details.

Serverless timeouts and when to queue

On a serverless host, your handler has a time limit. A single text finishes well inside it, but a loop over 500 contacts may not. Anything bigger than a handful of sends belongs in a background job or a queue, with the route handler only enqueuing. For a list, POST /v1/messages/bulk sends one body to up to 100 numbers per call, and the bulk docs have the rest.

Receiving replies

Texting is two-way, so you'll want a webhook route too. Create app/api/sms-webhook/route.ts, read the body with await req.text() before parsing so signature checks see the exact bytes, acknowledge with a 2xx quickly, and do the real work later. Event names, payload fields and signature headers are in the docs quickstart at docs.tryready.com, and our inbound webhooks guide covers the patterns. To test it before deploying, see testing webhooks locally.

Checklist before you ship

  • Key in a server-only variable with no NEXT_PUBLIC_ prefix.
  • Authenticated, rate-limited route.
  • Phone numbers normalized to E.164 first (formatting guide).
  • Idempotency key from a business identifier.
  • A timeout on fetch.
  • Consent captured in your own database; consent_attested is your statement, not a stored record of the contact's opt-in.

Cost

A segment on the Standard rate is $0.0075 plus a $0.0045 carrier fee, passed through at cost, excluding optional screening. An account can send up to 500 texts a month before registering for 10DLC. See pricing.

FAQ

Can I call the SMS API from a client component?

You shouldn't. Anything in client code can be read by anyone, including your API key. Call your own route handler or server action from the client and let the server talk to the SMS API.

Route handler or server action for sending texts?

Use a server action when a form in your own app triggers the text. Use a route handler when something else calls you, such as a mobile app, a cron service or another backend.

Does this work in the Edge runtime?

The calls above use fetch and AbortSignal.timeout, which Edge supports. randomUUID from node:crypto doesn't, so use crypto.randomUUID() from the Web Crypto global there.

The short version

Keep the key on the server, authenticate the route, derive idempotency keys from your own IDs and queue anything large. The Node.js guide has the lower-level version.