Hono
Middleware, Result-aware handlers and REST resources matching your OpenAPI document.
import { createHono } from "better-supabase/hono";
import { betterSupabase } from "./lib/supabase";
const bsb = createHono(betterSupabase);
const app = bsb
.app()
.use("/api/*", bsb.middleware())
.get("/api/me", (c) => c.json({ kind: c.var.auth.kind }));
export default app;createHono(betterSupabase) is createServer plus the pieces
below, so bsb.admin() and bsb.actingAs() work too. bsb.app() is
new Hono<typeof bsb.Env>() with bsb.onError installed.
typeof bsb.Env is the app's Hono Env, inferred from the definition, for
sub-apps and helpers that take a Context:
import type { Context } from "hono";
import { Hono } from "hono";
type Env = typeof bsb.Env;
const admin = new Hono<Env>();
const tenantOf = (c: Context<Env>) =>
c.var.auth.kind === "user" ? c.var.auth.claims.tenant_id : undefined;bsb.Env holds only a type and is undefined at runtime. HonoEnv<Models, Functions, unknown> is the same type with the generics written out.
Middleware
bsb.middleware() resolves the caller (Bearer header first, then the session
cookie), rejects anyone not in allow with Problem Details, and sets:
| Variable | Value |
|---|---|
c.var.db | Repositories bound to the caller; RLS applies |
c.var.auth | The resolved AuthState |
c.var.bsb | The full server context, including supabase and sql |
app.use("/public/*", bsb.middleware({ allow: ["user", "none"] }));
app.use("/app/*", bsb.middleware({ refresh: true })); // browser routes with cookiesTokens are verified locally against the cached JWKS, so the middleware makes
no network call. refresh: true refreshes an expiring cookie session and
adds the new cookies to the response. It is for routes browsers call with
cookies; bearer tokens never refresh.
Entry arrays with toHono
bsb.middleware() runs withBetterSupabase in
Hono's middleware slot. To compose it with other @supabase/middleware
entries (withPostgresClient, withCors, your own), pass the array to
toHono. Every contributed key lands on c.var, and Hono's response passes
back through the entries, so refreshed cookies and response headers reach it:
import { Hono } from "hono";
import { withPostgresClient } from "@supabase/server/middleware/postgres";
import { toHono } from "better-supabase/hono";
import { createServer, withBetterSupabase } from "better-supabase/server";
const bsb = createServer(betterSupabase);
const app = new Hono()
.use(
toHono([
withBetterSupabase(bsb, { allow: ["user"] }),
withPostgresClient(),
]),
)
.get("/api/notes", async (c) =>
c.json(await c.var.db.notes.list().orThrow()),
);Chain .use() into the routes it gates: Hono carries the contributed keys
through the chained call's type. c.env seeds the pipeline, so on Workers
getEnv inside the entries reads the bindings.
@supabase/server/adapters/hono is deprecated upstream and removed on
2026-12-01. Replace withSupabase from it with toHono([withBetterSupabase(bsb)]),
which contributes the same jwtClaims, userClaims and authMode keys.
Typed claims
When the definition has .claims(schema),
c.var.auth, c.var.bsb and the handler context are typed by the schema's
output, and so is profile with .userMetadata(schema). bsb.app() and
typeof bsb.Env carry both types; with a hand-written HonoEnv, pass the
claims as its fourth parameter:
const app = bsb
.app()
.use("/api/*", bsb.middleware())
.get("/api/role", (c) =>
c.json({
role: c.var.auth.kind === "user" ? c.var.auth.claims.user_role : null,
}),
);Handlers
bsb.handler unwraps what the handler returns:
- A
ResultorAsyncResultbecomes JSON on success, or Problem Details on failure. undefinedbecomes204.- A
Responseis sent as is. - A thrown
DbExceptionbecomes its Problem Details.
app.get(
"/api/customers/:id",
bsb.handler((c, { db }) => db.customers.get(c.req.param("id"))),
);
app.post(
"/api/customers",
bsb.handler(async (c, { db }) => db.customers.create(await c.req.json()), {
status: 201,
}),
);bsb.onError handles errors thrown outside bsb.handler. It sends a
DbException as its Problem Details, returns the response of Hono's
HTTPException unchanged, and sends anything else as a 500 without internal
details (unless exposeErrors).
Event sink sends a handler started (see
event sinks) go to
c.executionCtx.waitUntil on Workers. On other runtimes that stop the
invocation after the response, pass the runtime's function:
const bsb = createHono(betterSupabase, {
waitUntil: (promise) => EdgeRuntime.waitUntil(promise),
});Rate limits
bsb.rateLimit() counts one hit per request with
createRateLimit and adds the
RateLimit response field. With a rule, it also adds RateLimit-Policy.
A refused request gets a problem+json 429 with Retry-After, and key
returning undefined skips the limit:
import { createRateLimit } from "better-supabase/rate-limit";
const limiter = createRateLimit({ sql: postgres.admin });
app.use(
"/api/*",
bsb.rateLimit({
limiter,
scope: "api",
rule: { max: 100, period: "1 minute" },
key: (c) => c.req.header("x-api-key"),
}),
);Without rule, the scope's rule from set_rate_limit applies. policy
names the policy in the headers (default: the scope). A limiter error
answers with its status unless failOpen is set.
Resources
bsb.resource(table) mounts REST routes that match what
defineApi documents: the same paths, status codes and
bodies.
import { defineListQuery } from "better-supabase/list";
const customerList = defineListQuery(betterSupabase, "customers", {
search: ["name"],
facets: { status: "status" },
sorts: { name: { name: "asc" }, newest: { createdAt: "desc" } },
defaultSort: "newest",
});
app.route(
"/api/customers",
bsb.resource("customers", {
list: customerList,
select: ["id", "name", "status"],
input: { create: CustomerInput, update: CustomerPatch },
}),
);| Route | Operation | Success |
|---|---|---|
GET / | list: the list query, or page/size | 200 page |
POST / | create | 201 row |
GET /:id | get | 200 row, 404 when RLS hides it |
PATCH /:id | update | 200 row |
DELETE /:id | delete | 204 |
Views get list and get only. Limit operations with operations; other
methods answer 405 with an Allow header. Integer keys are parsed and
validated. input schemas (any Standard Schema) validate bodies before they
reach the repository.
A cross-site browser request that writes without a bearer token and without
Content-Type: application/json (a form post riding on the session cookie)
gets a 403 with code: "CROSS_SITE_REQUEST". JSON requests from other
origins need a CORS preflight, so your CORS settings decide those. Malformed
keys and bodies answer 400 invalid_input with the reason in detail.
Pass the same options to defineApi(betterSupabase, { resources: { customers: options } })
and the document describes exactly these routes.
Resources also take hooks for business logic around each operation,
actions for custom routes (typed with defineAction from
better-supabase/hono), output when a hook changes the response shape,
and permissions that the server's authorizer checks:
import { createHono, defineAction } from "better-supabase/hono";
const bsb = createHono(betterSupabase, { authorizer });
app.route(
"/api/customers",
bsb.resource("customers", {
permissions: { delete: "customers.delete" },
actions: {
archive: defineAction({
method: "POST",
path: "/{id}/archive",
permission: "customers.archive",
handler: (ctx, { id }) =>
ctx.db.customers.update(String(id), { status: "archived" }),
}),
},
}),
);A denied permission answers 403 with code: "PERMISSION_DENIED", or
APPROVAL_REQUIRED when the authorizer asks for an approval. See
Resources for hooks, actions and how list
filters rows, and Authorizers for the
contract.
Testing against the local stack
signLocalJwt from better-supabase/testing signs a token with the local
stack's ES256 key (see signing key). The API
verifies it against the stack's JWKS, as it would in production, and sees
the same claims that PostgREST and RLS see:
import { signLocalJwt } from "better-supabase/testing";
const bsb = createHono(betterSupabase);
const token = await signLocalJwt({ sub: userId, tenant_id: organizationId });
await app.request("/api/customers", {
headers: { authorization: `Bearer ${token}` },
});Session snapshot
bsb.middleware() sets c.var.snapshot to the verified user, or null.
bsb.contextFromSession(c.var.snapshot) builds a context from it with no
second verification and no header read, for work that runs outside the
handler's own context:
app.get("/notes", async (c) => {
const { db } = await bsb.contextFromSession(c.var.snapshot);
return c.json(await db.notes.list().orThrow());
});A snapshot holds the access token: never return it in a response. A copy of
it gets the invalid context, so pass plain values such as the user id
onward instead.
Last updated on