Add a route

You need: a scaffolded project. That is all.

Where your routes live

The Worker contract is what mounts them, project structure is where the file goes, protecting a route is the next step, and errors is what a handler throws.

In your app capability — the one pithy init scaffolded for you — you declare every method and path, and hand the Worker a loader for the module that mounts them:

// apps/api/pithy.config.ts
const app = defineCapability({
  name: "app",
  requiredBindings: [],
  routes: {
    declared: [{ method: "GET", path: "/boards" }],
    load: async () => (await import("./src/routes")).mountRoutes,
  },
});

The module mounts them on the Hono app it is handed:

// apps/api/src/routes.ts
import { requireAuth } from "@pithy-sh/auth/src/http/middleware";
import type { RouteMount } from "@pithy-sh/core/src/http/lazyRoutes";
import { describeRoute } from "@pithy-sh/core/src/http/routeSpec";

export const mountRoutes: RouteMount = (app) => {
  app.get(
    "/boards",
    describeRoute({
      summary: "List the boards.",
      verification: ["bearer", "session"],
      responses: { 200: BoardList },
    }),
    requireAuth(),
    async (c) => {
      const rows = await c.var.db.app.selectFrom("boards").selectAll().execute();
      return c.json({ boards: rows });
    },
  );
};

Your app is a capability like any other. It composes last, which is what makes the ordering rules below work in your favor.

Declare every route, and load the module on first use

The Worker imports your routes on the first request that reaches one, not at startup. Cloudflare refuses a version whose startup runs past its CPU limit, and every route module, every Zod schema it builds and everything it imports costs startup CPU when it is evaluated. So the Worker registers the declared paths when it starts, and builds the module the first time a request matches one. That request still passes every middleware it would have: CORS, the base context, every capability’s middleware, and the readiness guards.

  • declared lists every method and path the module mounts. A route mounted with app.all is declared with the method ALL. A path you mount and do not declare is one no request reaches.
  • load imports the module and returns its mount, (app, host) => void. The module loads once, however many first requests arrive together, and a load that fails is tried again on the next request.
  • Import the module only from load. A static import of ./src/routes anywhere in pithy.config.ts puts it back in the startup bundle, whatever the loader says.
  • routes as a function, routes: (app) => { … }, is refused when the Worker assembles, with a message naming the { declared, load } shape.

Hold the table to the module in a test. routeDrift(routes) from @pithy-sh/core/src/http/lazyRoutes loads the module and compares what it mounts against what you declared:

import { routeDrift } from "@pithy-sh/core/src/http/lazyRoutes";

test("declares exactly what it mounts", async () => {
  expect(await routeDrift(app.routes!)).toEqual({ undeclared: [], unmounted: [] });
});

An app small enough that its startup does not matter can skip the table: routesOf(mountRoutes) builds { declared, load } from a mount already in memory, reading the table off the mount itself. Nothing is deferred, so it saves no startup.

Say what the route is for, and what it returns

describeRoute goes first on the route line, ahead of the guards. Unless it declares a power or a rateLimit, it does nothing when it runs; what it carries is read by pithy contract, which writes the Worker’s OpenAPI document for every client to generate from.

  • summary is one sentence: the operation’s title in the document.
  • verification names what the guards enforce. A list where requireAuth() takes a bearer token or a session, which is most routes.
  • responses maps each success status to a Zod schema, or to { description, contentType } for bytes, HTML, a redirect or an empty body. Errors are never listed: every route can answer with the one error body, and the document says so once.
  • power, optional, names the power a caller’s role must hold, and declaring it installs the gate: a caller whose role in their acting organization does not hold it gets a 403, an anonymous one a 401.
  • rateLimit, optional, is { key, limit, period }: how many requests each caller may make in 10 or 60 seconds. It installs a gate too, after the power gate, and past the limit the route answers rate_limit/exceeded (429). key: "user" counts each signed-in user and key: "ip" each client address. A user limit on a route whose verification admits anyone but a bearer or session caller is refused whenever the route table is read: pithy worker sync and pithy deploy refuse it naming the route, and the Worker refuses the first request to your routes. pithy worker sync writes the binding that enforces it. A Worker missing that binding fails the first request to your routes naming it, and never serves the route unlimited. The document states the limit as x-pithy-rate-limit.
  • operation and tool, optional, opt the route in as a tool on your app’s MCP endpoint: operation is its permanent name, and tool is true on a GET or { effect } on anything else. Letting your users’ agents in has the rules.

Describe each field with .describe(), and the description travels into every generated client. A route with no describeRoute still lands in the document, written from its validators alone and marked x-pithy-undescribed, and pithy contract lists it so you know which ones to finish.

Guards before validators, always

app.post("/boards", describeRoute({ … }), requireAuth(), validate("json", CreateBoard), handler);

The seams are already on the request

c.var.authThe resolved identity, or null — typed never null in a handler chained after requireAuth()
c.var.dbYour Kysely instances, by binding
c.var.tThe translator — present whether or not you composed i18n
c.var.moderatorThe text check for what one person writes and others see — present with or without config
c.var.emitThe audit seam — a no-op with no audit capability
c.var.logThe request logger
c.var.entitlementsThe entitlement resolver

None of them needs a conditional. An uncomposed seam is present and inert, so c.var.emit(...) from a project with no audit capability is a call that does nothing rather than a crash.

Gating

app.get("/reports", requireAuth(), requireEntitlement("pro"), handler);

requireAuth() first. An entitlement gate on an anonymous caller should answer 401, not 403 — sign in and you may not are different instructions.

Validate at the boundary

One Zod schema, and the failing issues come back in the payload so a form can highlight the field:

import { validate } from "@pithy-sh/core/src/http/validation";

validate("json", CreateBoard)

The handler reads the parsed value with c.req.valid("json"). validate is zValidator from @hono/zod-validator with two things added: the failure hook that turns a parse failure into validation/invalid_input rather than a bare 400, and the schema left readable on the middleware. That second part is what puts the route’s input in the OpenAPI document. A bare zValidator still validates, but the document cannot see its schema, so no generated client learns that part of the request.

Throw, do not construct a response

throw new NotFoundError({ message: "That board does not exist.", params: { board: key } });

Model a failure as a code plus params, never a message alone. A message with the value baked in is one string a client can only print; a code with params is a sentence any client can rewrite in any language — and the English still arrives on the wire for the ones that will not.

Middleware of your own

defineCapability({
  name: "app",
  middleware: [
    (app) => {
      app.use("/support/feedback", async (c, next) => { /* your rule */ await next(); });
    },
  ],
});

Every capability’s middleware mounts before any capability’s routes, and your app composes last — so yours runs after auth has resolved the session and before another capability’s own gate.

Write the path from the base path you configured. A mount point you moved and a middleware path you did not is a gate that silently stops covering anything.

Your route is a peer, not a wrapper

Nothing stops you reading a capability’s tables directly, or serving an object with your own authorization. The capability’s routes stay scoped to the caller; yours can be scoped to anything.

ESC