A small API that does not depend on where it runs
A REST API with login, a data store and input validation usually calls for a framework, a database
driver and a handful of libraries. Hono lets you write it as a function that receives a
Request and returns a Response, the same objects the web uses, and run it
on different runtimes. That is the sense of "edge" this article defends: not that Bun runs on the
edge, but that the API code knows nothing about the runtime. You choose the runtime at the last moment.
Here I build an API with three functions: a login that issues a JWT token, a list of articles
protected by the token, and an insert validated with Zod. I ran everything with Bun 1.4.4 and Node 24.11.0
(November 2026), with Hono 4.13.18, @hono/zod-validator 0.9.1 and Zod 4.6.7. The tests
call the application's fetch method directly, without opening ports, so the results can
be reproduced anywhere. If you are coming from this series: we covered SQLite in the article
on SQLite and Redis in Bun, and the comparison with the other
runtimes is in Bun, Node and Deno.
Setup: three packages
The project starts from a package.json with "type": "module" and a single
install command. Pinning the versions (the lockfile does it for you) matters more than usual here, because the
middleware APIs change between minor versions: as we will see, the JWT middleware today requires
an option that many tutorials do not know about.
$ bun add hono @hono/zod-validator zod
installed hono@4.13.18
installed @hono/zod-validator@0.9.1
installed zod@4.6.7
3 packages installed
Hono is the framework, Zod describes and checks the shape of the data, and @hono/zod-validator
connects them as middleware. Nothing else is needed: JWT, CORS and error handling are already inside Hono, and
SQLite comes from the runtime.
The application: a function that receives its dependencies
The app.ts file exports a creaApp function instead of a ready-made
application. The two things that change between environments, the data store and the secrets, come in as
arguments. This lets you test the API with an in-memory store, run it in production with
SQLite, and never write the secrets into the code.
import { timingSafeEqual } from "node:crypto";
import { Hono } from "hono";
import { HTTPException } from "hono/http-exception";
import { jwt, sign } from "hono/jwt";
import { zValidator } from "@hono/zod-validator";
import { z } from "zod";
export interface Articolo { id: number; title: string; text: string }
export interface Store {
elenco(): Articolo[];
crea(title: string, text: string): Articolo;
}
const NuovoArticolo = z.object({
title: z.string().min(5).max(200),
text: z.string().min(10),
});
const uguali = (a: string, b: string) => {
const x = Buffer.from(a), y = Buffer.from(b);
return x.length === y.length && timingSafeEqual(x, y);
};
export function creaApp(store: Store, env: { JWT_SECRET: string; ADMIN_PASSWORD: string }) {
const app = new Hono();
app.get("/health", (c) => c.json({ status: "ok" }));
app.post("/login", async (c) => {
const { password } = await c.req.json().catch(() => ({ password: "" }));
if (typeof password !== "string" || !uguali(password, env.ADMIN_PASSWORD)) {
return c.json({ error: "invalid credentials" }, 401);
}
const scadenza = Math.floor(Date.now() / 1000) + 15 * 60; // 15 minutes
return c.json({ token: await sign({ sub: "admin", exp: scadenza }, env.JWT_SECRET, "HS256") });
});
// Everything under /api requires a valid token
app.use("/api/*", jwt({ secret: env.JWT_SECRET, alg: "HS256" }));
app.get("/api/articoli", (c) => c.json(store.elenco()));
app.post("/api/articoli", zValidator("json", NuovoArticolo), (c) => {
const { title, text } = c.req.valid("json");
return c.json(store.crea(title, text), 201);
});
app.onError((err, c) => {
// 401, 403, 400 thrown by middleware are HTTPException: they already carry their response
if (err instanceof HTTPException) return err.getResponse();
console.error(err); // the detail stays in the log, the client does not get it
return c.json({ error: "internal error" }, 500);
});
return app;
}
The parts that matter, in order. The Store interface describes what the API asks of the
store (list and create) without saying how: it is what lets you swap SQLite for something else. The
login compares the password with timingSafeEqual from node:crypto, which takes
constant time: a comparison with === stops at the first differing character, and the response
time can reveal how many characters were right. The token gets a 15-minute expiry in the
exp claim, which RFC 7519 defines as the moment after which the token must not be
accepted. The jwt middleware protects everything under /api, while
/health and /login stay public because the middleware is attached only to the /api/* path.
The validation is declared in the NuovoArticolo schema: a title of 5 to 200 characters,
a text of at least 10. zValidator("json", ...) applies it before the handler, which therefore
receives data that is already checked and typed through c.req.valid("json"). If the check fails,
it answers 400 without your code running. The limits here are examples of mine, not a Hono rule:
decide them based on what your database and your interface can accept.
The stores: SQLite for the runtime, memory for the tests
The SQLite implementation uses bun:sqlite, so it runs only with Bun. It opens the database in
strict mode, turns on WAL, and prepares the two statements once. RETURNING
makes the INSERT return the row it just created, with the assigned identifier, without a
second query.
import { Database } from "bun:sqlite";
import type { Articolo, Store } from "./app.ts";
export function storeSqlite(file = ":memory:"): Store {
const db = new Database(file, { strict: true });
db.run("PRAGMA journal_mode = WAL");
db.run(`CREATE TABLE IF NOT EXISTS articoli (
id INTEGER PRIMARY KEY, title TEXT NOT NULL, text TEXT NOT NULL)`);
const tutti = db.query("SELECT id, title, text FROM articoli ORDER BY id");
const inserisci = db.query(
"INSERT INTO articoli (title, text) VALUES ($title, $text) RETURNING id, title, text",
);
return {
elenco: () => tutti.all() as Articolo[],
crea: (title, text) => inserisci.get({ title, text }) as Articolo,
};
}
The in-memory version (store-memoria.ts, an array with a counter) has the same shape
and runs anywhere. It has a precise job: the API tests must not depend on a file on disk, and
the cross-runtime portability test cannot import a module that exists only in Bun.
Testing it without starting a server
A Hono application has a fetch(request) method. Calling it is equivalent to receiving an
HTTP request, but without the network: ideal for tests and for this article, which opens no ports. The script
builds the requests, passes them to the app and prints the status and the start of the body. It includes the cases that matter
in a protected API: no token, wrong credentials, invalid data, a tampered token
and a correctly signed token that has expired.
import { sign } from "hono/jwt";
import { creaApp } from "./app.ts";
import { storeInMemoria } from "./store-memoria.ts";
const env = { JWT_SECRET: "secret-for-the-test-only", ADMIN_PASSWORD: "test-password" };
const store = process.env.STORE === "sqlite"
? (await import("./store-sqlite.ts")).storeSqlite()
: storeInMemoria();
const app = creaApp(store, env);
// app.fetch takes a Request and returns a Response: no port is opened
async function chiama(metodo: string, percorso: string, corpo?: unknown, token?: string) {
const res = await app.fetch(new Request(`http://prova${percorso}`, {
method: metodo,
headers: {
...(corpo ? { "content-type": "application/json" } : {}),
...(token ? { authorization: `Bearer ${token}` } : {}),
},
body: corpo ? JSON.stringify(corpo) : undefined,
}));
return { stato: res.status, testo: await res.text() };
}
const riga = (etichetta: string, r: { stato: number; testo: string }) =>
console.log(`${etichetta.padEnd(18)}${r.stato} ${r.testo.slice(0, 60)}`);
const runtime = typeof Bun !== "undefined" ? `bun ${Bun.version}` : `node ${process.versions.node}`;
console.log(`${runtime}, store ${process.env.STORE ?? "memory"}`);
riga("health", await chiama("GET", "/health"));
riga("api no token", await chiama("GET", "/api/articoli"));
riga("wrong login", await chiama("POST", "/login", { password: "no" }));
const login = await chiama("POST", "/login", { password: env.ADMIN_PASSWORD });
const token = JSON.parse(login.testo).token as string;
console.log("token".padEnd(18) + `${login.stato} ${token.split(".").length} dot-separated parts`);
riga("create valid", await chiama("POST", "/api/articoli", { title: "First article", text: "A sufficiently long text" }, token));
riga("create invalid", await chiama("POST", "/api/articoli", { title: "x" }, token));
riga("list", await chiama("GET", "/api/articoli", undefined, token));
riga("tampered token", await chiama("GET", "/api/articoli", undefined, token.slice(0, -2) + "xx"));
// A correctly signed token that has already expired (exp one hour ago)
const scaduto = await sign({ sub: "admin", exp: Math.floor(Date.now() / 1000) - 3600 }, env.JWT_SECRET, "HS256");
riga("expired token", await chiama("GET", "/api/articoli", undefined, scaduto));
// Output:
// bun 1.4.4, store memory
// health 200 {"status":"ok"}
// api no token 401 Unauthorized
// wrong login 401 {"error":"invalid credentials"}
// token 200 3 dot-separated parts
// create valid 201 {"id":1,"title":"First article","text":"A sufficiently long
// create invalid 400 {"success":false,"error":{"name":"ZodError","message":"[\n
// list 200 [{"id":1,"title":"First article","text":"A sufficiently long
// tampered token 401 Unauthorized
// expired token 401 Unauthorized
The nine result lines say the system behaves as it should: 401 without a token, 401 with a wrong password (without saying whether the user or the password was at fault), 201 on creation, 400 on invalid data, and 401 for both the tampered token and the expired one. The body of the 400 response is Zod's error as is, with the library's internal structure: for a public API it is better to replace it with a message of your own, because it exposes details that the caller does not need.
I verified the portability, I did not assume it. I re-ran the same prova.ts with
STORE=sqlite bun prova.ts and with node prova.ts (Node 24 runs TypeScript
directly, see the comparison article): the nine lines after the header are identical byte
for byte, and I compared the three outputs with a checksum. The Hono application is the same;
only the store changes, and the SQLite one works only with Bun.
Two traps I found by running it
The first: Hono's JWT middleware requires the alg option, the signing algorithm. Many
examples online omit it because they date from earlier versions; with 4.13 Hono refuses to
register the middleware. The second is less obvious. A global onError that turns
everything into a 500 also intercepts the HTTPExceptions that middleware throws to signal 401
and 403: a request without a token would return 500 instead of 401, and your alarms on 500s
would go off at every scan. The script reproduces both.
import { Hono } from "hono";
import { jwt } from "hono/jwt";
// 1) jwt() without the algorithm: Hono refuses to start
try {
// @ts-expect-error alg is required in the type
new Hono().use("/api/*", jwt({ secret: "s" }));
} catch (e) {
console.log("without alg:", (e as Error).message);
}
// 2) onError that turns every error into a 500, including the middleware's 401s
const app = new Hono();
app.use("/api/*", jwt({ secret: "s", alg: "HS256" }));
app.get("/api/x", (c) => c.text("ok"));
app.onError((_err, c) => c.json({ error: "internal error" }, 500));
const res = await app.fetch(new Request("http://prova/api/x"));
console.log("naive onError, request without token ->", res.status);
// Output:
// without alg: JWT auth middleware requires options for "alg"
// naive onError, request without token -> 500
The message from the first test says which option is missing, and the number from the second is the bug: 500 where
there should be 401. The remedy is in the version of app.ts above: inside
onError, if the error is an HTTPException you return its response with
err.getResponse(), as the documentation describes, and only for the other errors
do you log the detail and answer with a generic message. The detail must never go to the
client: a stack trace in a response tells an attacker how your code is built.
Starting it: the main file exports fetch
To make the API listen, Bun does not require an explicit Bun.serve: if the main file
exports as default an object with fetch and, optionally, port, it starts the
server by itself. The index.ts file reads the secrets from the environment and refuses to start if they are missing,
rather than falling back to a convenient value: a development secret forgotten in production is one
of the most common ways of making token signing worthless.
import { creaApp } from "./app.ts";
import { storeSqlite } from "./store-sqlite.ts";
const { JWT_SECRET, ADMIN_PASSWORD, DB_FILE = "dati.db", PORT = "3000" } = process.env;
if (!JWT_SECRET || !ADMIN_PASSWORD) {
throw new Error("JWT_SECRET and ADMIN_PASSWORD are required in the environment");
}
const app = creaApp(storeSqlite(DB_FILE), { JWT_SECRET, ADMIN_PASSWORD });
// Bun starts a server by itself if the main file exports { fetch }
export default { port: Number(PORT), fetch: app.fetch };
I did not start this listing as a server, because it would open a port; I did, however, import its
module from a separate script to check the two things that do not depend on the network. Without the
environment variables the import fails with "JWT_SECRET and ADMIN_PASSWORD are required in the
environment". With the variables set, the module exports port 3000 and a
fetch function that answers 200 on /health. The behavior of listening on the port,
instead, is the one described by the Bun and Hono documentation, and you need to test it yourself.
What "edge" means here, and where it ends
The Hono documentation presents the framework as built on web standards, and includes
getting-started guides for Bun, Cloudflare Workers and other environments. In practice this means that
creaApp can be moved to a low-startup runtime without rewriting it. There are three things to know
before saying "it runs on the edge".
- The database:
bun:sqliteexists only in Bun; on another runtime the store must be rewritten with what that runtime offers. - The state: an in-memory array lives as long as the process, and if there is more than one instance each has its own.
- The secrets: every platform has its own way of passing them; the
creaAppfunction receives them as an argument for exactly this reason.
The common thread is that portability concerns the route code, not the infrastructure around it. Your
job is to keep the routes clean of everything runtime-specific and to put what is
specific behind small interfaces, like the Store here. I tested the code on Bun and
Node; I did not test it on Cloudflare Workers, and whoever uses it must verify their own limits.
Frequently asked questions
Does Hono also work on Node?
Yes as far as the application goes: the same prova.ts was run with Node 24 and
with the in-memory store, giving the same responses. To make Hono listen on Node you need a dedicated
adapter, which I did not try here. The SQLite store, instead, depends on Bun.
Can I keep the token in a cookie instead of the header?
Hono's JWT middleware supports it, with an option for the cookie name, and the middleware code
I read contains the cookie branch. A cookie protects against being read through JavaScript if
it is HttpOnly, but it exposes you to requests from other sites, so it requires an additional
defense; the Authorization header does not have that problem.
How do I invalidate a token before it expires?
With a signed JWT you cannot, until the secret changes or you keep a list of revoked tokens. That is why the expiry is short (here 15 minutes): it is the cost you accept in exchange for not querying the database on every request.
What you can do now
You can structure a Hono API as a function that receives its dependencies, protect it with a JWT
that expires and is compared in constant time, validate data before the handler, test it by calling
fetch without opening ports, and recognize the two traps that make it answer 500 instead of
401. The next step is putting it in a container:
Bun in production with Docker and Kubernetes.
Sources
- Hono, "Bun" - starting a Hono application with Bun through
export default; consulted on 2026-11-12 - Hono, "JWT Auth Middleware" - the middleware's
secretandalgoptions; consulted on 2026-11-12 - Hono, "Exception" -
HTTPExceptionandgetResponse()insideonError; consulted on 2026-11-12 - Hono, "Web Standards" - the framework built on web standards and portable across runtimes; consulted on 2026-11-12
- Bun Docs, "HTTP server" - the
export defaultsyntax for starting the server; consulted on 2026-11-12 - RFC 7519, "JSON Web Token (JWT)" - meaning of the
expclaim; consulted on 2026-11-12

Commenti
Caricamento commenti...
Sign in to comment