To send an SMS from Hono, add a POST route that validates the input, reads the API key with env(c), and calls the REST API with plain fetch. Hono is built on web-standard APIs, so the same handler runs on Node, Bun, Deno and Cloudflare Workers without changes.
We make Ready, so the code uses the Ready API and only the request shape we document. If you're on a specific runtime and want its own setup, we also have guides for Cloudflare Workers and Deno and Bun. This one is about the Hono layer on top.
Why env(c) instead of process.env
Workers has no process.env. It hands you bindings on the context. Hono's env() helper from hono/adapter reads from the right place on each runtime, so the key lookup is the one line that doesn't change between hosts.
import { env } from 'hono/adapter';
type Bindings = { READY_API_KEY: string; INTERNAL_TOKEN: string }; On Workers, set the key with wrangler secret put READY_API_KEY. On Node or Bun, set READY_API_KEY in the environment. Keep it out of the repo. Our guide to API key security and rotation covers storage and rotation.
The route
Install hono, zod and @hono/zod-validator, then:
import { Hono } from 'hono';
import { env } from 'hono/adapter';
import { bearerAuth } from 'hono/bearer-auth';
import { HTTPException } from 'hono/http-exception';
import { zValidator } from '@hono/zod-validator';
import { z } from 'zod';
type Bindings = { READY_API_KEY: string; INTERNAL_TOKEN: string };
const schema = z.object({
to: z.string().regex(/^\+[1-9]\d{7,14}$/),
body: z.string().min(1).max(1600),
});
const app = new Hono();
app.use('/sms', bearerAuth({
verifyToken: async (token, c) => token === env<Bindings>(c).INTERNAL_TOKEN,
}));
app.post('/sms', zValidator('json', schema), async (c) => {
const { READY_API_KEY } = env<Bindings>(c);
const key = c.req.header('Idempotency-Key') ?? crypto.randomUUID();
const payload = JSON.stringify({ ...c.req.valid('json'), consent_attested: true });
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': READY_API_KEY,
'Idempotency-Key': key,
},
body: payload,
signal: AbortSignal.timeout(8_000),
});
if (res.ok) return c.json({ sent: true, key });
status = res.status;
if (status !== 429 && status < 500) break;
} catch {
status = 0;
}
await new Promise((r) => setTimeout(r, 300 * 2 ** attempt));
}
if (status === 409) throw new HTTPException(409, { message: 'Quiet hours: send again later' });
if (status >= 400 && status < 500) throw new HTTPException(422, { message: 'Text not sent' });
throw new HTTPException(502, { message: 'Texting service unavailable' });
});
export default app; export default app is all Bun and Workers need: both call the default export's fetch. On Node, add @hono/node-server and run serve(app).
Three details in that handler matter:
- The key comes from the caller's
Idempotency-Keyheader when it's there, and fromcrypto.randomUUID()when it isn't. Reuse the same key on every attempt inside the loop, and have your own clients reuse theirs when they retry, so nothing sends twice. - The loop retries a
429, any5xxand network errors. Other4xxanswers break out at once, since asking again won't change them. AbortSignal.timeoutkeeps a slow upstream from eating the whole request budget. Workers limits how long a request may run, so keep the attempts few and the timeouts short.
Set consent_attested to true only when the recipient agreed to receive texts.
What each answer becomes
| Ready answered | Meaning | Hono returns |
|---|---|---|
| 2xx | Accepted | 200 with the key |
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 |
A 409 isn't an outage. Treat it as "not now" and show it that way. The errors docs list every code, and our retries and failure handling guide turns them into a policy.
Testing the route
Hono apps are plain fetch handlers, so you can test one without a server:
const res = await app.request('/sms', {
method: 'POST',
headers: { Authorization: 'Bearer test-token', 'Content-Type': 'application/json' },
body: JSON.stringify({ to: '+12125550199', body: 'Your order #1042 has shipped.' }),
}, { READY_API_KEY: 'test', INTERNAL_TOKEN: 'test-token' }); The third argument is the env bindings. Stub global fetch first and you can assert on the headers without sending anything. Our mocking guide goes further.
Where this stops being enough
A handler that retries inside the request suits one text a user is waiting on. For bulk work, or when a failure must not drop the message, put a queue in front. On Workers that means a queue binding and a consumer; on Node or Bun it means something like BullMQ. Either way the consumer reuses the same fetch, with the same key stored on the job.
FAQ
Does this work on Cloudflare Workers?
Yes. It uses only fetch, AbortSignal and crypto.randomUUID(), which Workers provides. The one thing to change is where the key comes from, and env(c) already handles that.
Do I need the validator and bearer auth?
You need something on both. Validation rejects bad numbers before you call the API, and auth stops strangers from using your route to send texts. Swap in your own session or JWT middleware if you have one.
How do I receive replies?
Add a second route that reads the raw body with c.req.text(), verifies the signature, returns 200 fast, dedupes and enqueues the work. See the inbound webhook guide and the webhook docs on docs.tryready.com.
The short version
env(c) for the key, a validated and authenticated route, bounded retries with one idempotency key, and a 409 mapped to "not now". The messages API docs list every field, and you can sign up to get a key.