oRPC
A middleware that adds the caller's repositories to the oRPC context.
import { os } from "@orpc/server";
import { createOrpc, type OrpcRequestContext } from "better-supabase/orpc";
import * as v from "valibot";
import { betterSupabase } from "./lib/supabase";
export const bsb = createOrpc(betterSupabase);
const base = os.$context<OrpcRequestContext>();
const authed = base.use(bsb.middleware());
const open = base.use(bsb.middleware({ allow: ["user", "none"] }));
export const router = {
customers: {
list: authed.handler(({ context }) =>
bsb.unwrap(context.db.customers.list({ select: ["id", "name"] })),
),
rename: authed
.input(
v.object({ id: v.string(), name: v.pipe(v.string(), v.minLength(2)) }),
)
.handler(({ input, context }) =>
bsb.unwrap(context.db.customers.update(input.id, { name: input.name })),
),
},
health: open.handler(() => ({ ok: true })),
};Serve the router with bsb.fetchHandler. It passes the request as the
initial context, answers 404 when no procedure matches, and adds the
request's cookies to the response: refreshed session cookies with
middleware({ refresh: true }), and bsb-primary-until after a write when
read replicas are configured.
import { RPCHandler } from "@orpc/server/fetch";
export default {
fetch: bsb.fetchHandler(new RPCHandler(router), { prefix: "/rpc" }),
};Calling handler.handle(request, { context: { request } }) yourself also
works, but then those cookies never reach the client. An adapter without a
Request, such as the Node handler or a WebSocket peer, passes
{ context: { headers, url } } instead; the middleware builds the request
from them, once per Headers object. Read the request in a handler through
context.bsb or, in a rateLimit key, through its request argument.
Routes that only native apps and servers call can pass
middleware({ cookies: false }): the middleware then resolves bearer tokens
and API keys only, and never reads a session cookie a browser happens to send.
cookies: false with refresh throws a TypeError at setup. The same option
works on the Hono middleware and on handle().
On runtimes that stop the invocation after the response, pass waitUntil to
createOrpc; fetchHandler hands it the
event sink sends a
procedure started.
Serve the API
bsb.router(api, options) turns a defineApi model
into oRPC procedures, so the document and the server come from one
definition. Without resources and blocks, the API publishes every table
and every block instance betterSupabase.blocks(set) registered:
import { openapi } from "@orpc/openapi";
import { OpenAPIHandler } from "@orpc/openapi/fetch";
import { os } from "@orpc/server";
import { createOrpc, type OrpcRequestContext } from "better-supabase/orpc";
import { defineApi } from "better-supabase/spec";
import { betterSupabase } from "./lib/supabase";
export const api = defineApi(betterSupabase, {
info: { title: "CRM API", version: "1.0.0" },
basePath: "/api",
});
const bsb = createOrpc(betterSupabase);
const { procedures } = bsb.router(api, {
guard: { requireTenant: true },
meta: openapi,
});
export const handle = bsb.fetchHandler(
new OpenAPIHandler(os.$context<OrpcRequestContext>().router(procedures)),
);Each table gets its CRUD routes plus the contract verbs page, count,
aggregate and upsert as POST /<table>/<verb>. Each block instance gets
POST /<instance>/<method> for every method of its client, and
POST /<instance>/<member>/<method> for its sub-clients. A method that
takes more than one argument takes them as a JSON array. The client runs as
the caller, so RLS applies.
| Option | What it does |
|---|---|
guard | The middleware() options every procedure runs behind, permission included |
meta | Route metadata per procedure, such as openapi from @orpc/openapi |
resources | defineResource handlers by table key, to reuse hooks or actions you defined there |
routes lists the method, path and operation id of every procedure, and they
match the operations of api.openapi(). A block write takes the permission
in blocks.<instance>.permissions of defineApi, decided by the
authorizer. A failed call becomes an ORPCError with the DbError as
Problem Details, as bsb.unwrap does.
Entry arrays with toOrpc
toOrpc(entries, handler, { prefix }) runs an @supabase/middleware entry
array around an oRPC fetch handler. The procedures' initial context is
{ request } plus every contributed key, and the response passes back
through the entries, so refreshed cookies reach the client without
bsb.middleware():
import { RPCHandler } from "@orpc/server/fetch";
import { toOrpc } from "better-supabase/orpc";
import { createServer, withBetterSupabase } from "better-supabase/server";
const bsb = createServer(betterSupabase);
// The router's procedures read context.db.
const base = os.$context<{
request: Request;
db: ReturnType<typeof bsb.admin>;
}>();
export default {
fetch: toOrpc([withBetterSupabase(bsb)], new RPCHandler(router), {
prefix: "/rpc",
}),
};A refused caller gets the guard's 401 Problem Details before oRPC runs. Use
bsb.unwrap from createOrpc to turn a Result into an ORPCError.
Contract-first routers
With a contract from @orpc/contract, apply the same middleware to the
implementer. The client package imports only the contract, and the server
serves it over HTTP with OpenAPIHandler. This example mounts it on Hono:
import { oc } from "@orpc/contract";
import { openapi } from "@orpc/openapi";
import * as v from "valibot";
const customer = v.object({ id: v.string(), name: v.string() });
export const contract = {
customers: {
get: oc
.meta(openapi({ method: "GET", path: "/customers/{id}" }))
.input(v.object({ id: v.pipe(v.string(), v.uuid()) }))
.output(customer),
},
};import { OpenAPIHandler } from "@orpc/openapi/fetch";
import { implement } from "@orpc/server";
import type { OrpcRequestContext } from "better-supabase/orpc";
import { Hono } from "hono";
import { contract } from "./contract";
const os = implement(contract)
.$context<OrpcRequestContext>()
.use(bsb.middleware());
const router = os.router({
customers: {
get: os.customers.get.handler(({ context, input }) =>
bsb.unwrap(
context.db.customers.get(input.id, { select: ["id", "name"] }),
),
),
},
});
const handle = bsb.fetchHandler(new OpenAPIHandler(router), { prefix: "/api" });
export const app = new Hono().all("/api/*", (c) => handle(c.req.raw));OpenAPIHandler sends the error's status code, so a missing row answers
404 and a write that RLS rejects answers 403, each with the Problem Details
in the body's data. The .meta(openapi(...)) form needs no import for its
side effects; .route(...) works too after import "@orpc/openapi/extensions/route".
The oRPC example
has both styles.
Context
bsb.middleware() resolves the caller and rejects anyone not in allow
(default ['user']). It adds:
context.db: repositories bound to the caller, so RLS applies.context.auth: the resolvedAuthState.context.bsb: the full server context.
With .claims(schema) on the definition,
context.auth and context.bsb are typed by the schema's output:
export const role = authed.handler(({ context }) =>
context.auth.kind === "user" ? context.auth.claims.user_role : null,
);Rate limits
bsb.rateLimit() counts one hit per call with
createRateLimit. key gets
the context and the procedure path; returning undefined skips the limit.
Its type parameter is the context key reads, OrpcRequestContext by
default. bsb.fetchHandler
adds the RateLimit field to the response, plus RateLimit-Policy with a
rule. A refused call throws TOO_MANY_REQUESTS, and the response carries
Retry-After:
import { createRateLimit } from "better-supabase/rate-limit";
const limiter = createRateLimit({ sql: postgres.admin });
const limited = os.$context<OrpcRequestContext>().use(
bsb.rateLimit({
limiter,
scope: "rpc",
rule: { max: 60, period: "1 minute" },
key: ({ request, path }) => {
const key = request.headers.get("x-api-key");
return key === null ? undefined : `${key}:${path.join(".")}`;
},
}),
);The headers reach the client through bsb.fetchHandler, or through oRPC's
own handler when it uses ResponseHeadersHandlerPlugin: the middleware then sets
them on context.resHeaders.
To count one call against several limits, such as per user and per
organization, pass hits instead of scope and key. It returns the limits
for the call, and an empty list skips them. They count through
checkAll, so a refused
call leaves every counter as it was, and the RateLimit field lists each
limit under its scope:
bsb.rateLimit({
limiter,
hits: ({ request }) => {
const org = request.headers.get("x-org-id");
return org === null
? []
: [{ scope: "rpc:org", key: org, rule: { max: 600, period: 60 } }];
},
});When the procedure declares TOO_MANY_REQUESTS with .errors(), a refused
call throws the declared error, so a typed client sees it as defined, with the
problem details as its data. Set code to throw another declared code
instead.
Permissions
createOrpc takes the server's authorizer option. bsb.middleware() and
bsb.authed() take the guard options allow, aal and scopes, and the
checks requireTenant, roles, permission and authorize. A
permission is decided by that authorizer, with a resource of
{ type: "route" }:
import { createOrpc } from "better-supabase/orpc";
import * as v from "valibot";
import { authorizer } from "./lib/authorizer";
import { betterSupabase } from "./lib/supabase";
export const bsb = createOrpc(betterSupabase, { authorizer });
export const remove = bsb
.authed({ requireTenant: true, permission: "customers.delete" })
.input(v.object({ id: v.string() }))
.handler(({ input, context }) =>
bsb.unwrap(context.db.customers.delete(input.id)),
);To decide on the row the procedure acts on, put bsb.middleware() after
.input() and pass resource. It gets the validated input and the context
(db, session, tenant), and its return value is the resource the
authorizer sees (Load the resource):
export const rename = bsb
.authed()
.input(v.object({ id: v.string(), name: v.string() }))
.use(
bsb.middleware({
permission: "customers.update",
resource: async (input, { db }) => {
const { id } = v.parse(v.object({ id: v.string() }), input);
const row = await db.customers
.get(id, { select: ["id", "ownerId"] })
.orThrow();
return { type: "customer", id, properties: { ownerId: row.ownerId } };
},
}),
)
.handler(({ input, context }) =>
bsb.unwrap(context.db.customers.update(input.id, { name: input.name })),
);A refused caller gets an ORPCError with code FORBIDDEN and the Problem
Details in data: NO_TENANT, MISSING_ROLE, PERMISSION_DENIED,
APPROVAL_REQUIRED or NOT_AUTHORIZED. Without an authorizer, a procedure
with a permission refuses every caller. See
Authorizers for the contract and
defineAuthorizer.
Permissions in a contract-first router
bsb.authed() builds a procedure from scratch, so it doesn't apply to an
implementer from implement(contract). Guard the router with
bsb.middleware(), then add .use(bsb.middleware({ ... })) to each procedure
that needs more, with the same guard options:
const os = implement(contract)
.$context<OrpcRequestContext>()
.use(bsb.middleware());
const router = os.router({
customers: {
get: os.customers.get.handler(({ context, input }) =>
bsb.unwrap(context.db.customers.get(input.id)),
),
remove: os.customers.remove
.use(
bsb.middleware({ requireTenant: true, permission: "customers.delete" }),
)
.handler(async ({ context, input }) => {
await bsb.unwrap(context.db.customers.delete(input.id));
return { deleted: true };
}),
},
});The nested middleware reuses the request's resolved caller, so the second
guard verifies no token again. In both styles the authorizer passed to
createOrpc decides every permission. An authorization package plugs in
there, as the authorizer, instead of adding a guard of its own in front of
the procedures.
Errors
bsb.unwrap(result) returns the data, or throws an ORPCError when the
Result failed. It accepts a Result, an AsyncResult or a promise of
either, and the procedure's output type is the data type. The middleware also
converts thrown DbExceptions.
The error code comes from the error's HTTP status. For example not_found
becomes NOT_FOUND, conflict becomes CONFLICT, validation becomes
UNPROCESSABLE_CONTENT and stale becomes PRECONDITION_FAILED. The
error's data is the RFC 9457 Problem Details, so clients get the same
kind, code, constraint and issues fields as the HTTP adapters send.
import { safe } from "@orpc/client";
const [error, data] = await safe(client.customers.rename({ id, name }));
if (error?.data?.kind === "conflict") showTaken(error.data.constraint);Last updated on