Skip to content
brix.v2.15.0+b120c49

Search documentation

Loading search…

    Documentation menu
    Docs / APIs and data / API contractsRead Markdown
    On this page

    API server contracts and routes

    Define a universal typed API contract, implement its server-only route, and let Brix discover and register the endpoint.

    API handlers return JSON data, not native Response objects. Use a contract-first response route for a standalone redirect, download, stream, or non-JSON endpoint. JSON authentication failures normally use 401/403; a redirect followed by Fetch does not navigate the browser document.

    Define a contract

    #

    Start in a full-stack application with the project-bound factories exported from #brix and #brix/server. Generate the files before replacing their contents:

    brix add api updateProfile --feature profile
    
    src/features/profile/api/updateProfile/contract.ts
    import { createApiContract } from "#brix";
    import { z } from "brix/zod";
    
    export const updateProfileApiContract = createApiContract({
      method: "POST",
      path: "/api/profiles/:profileId",
      body: z.object({ displayName: z.string().min(1) }),
      response: z.object({ id: z.string(), displayName: z.string() }),
    });
    

    contract.ts exports exactly one runtime value, the *ApiContract; brix check rejects other runtime exports there. Export a schema shared with other modules from a separate file, such as schemas.ts, and import it into the contract.

    Path parameters are inferred from :profileId. GET contracts cannot have a body. Body and query callers provide schema input; handlers receive parsed output. A response schema describes JSON wire input, while clients receive its parsed output.

    JSON bodies and responses are serialized before validation, so their schemas must accept JSON values. A Date passed to z.date() arrives as an ISO string and fails, a bigint cannot be serialized, and Map or Set values become {}. Contract creation throws an error naming the field for z.date(), z.instanceof(Date) (or any class other than Object and Array), z.bigint(), z.map(), z.set(), z.symbol(), and z.nan() body and response fields. The check runs when the module defining the contract loads, not in TypeScript, so generic contract factories keep compiling. A union passes when one branch accepts JSON. Use z.iso.datetime() (add .transform((value) => new Date(value)) for a Date output) or z.coerce.date(), strings for large integers, z.record() instead of maps, and z.array() instead of sets.

    Query schemas read URL strings, so declare numbers with z.coerce.number() and booleans with z.stringbool(); contract creation rejects z.number(), z.boolean(), z.date(), z.coerce.boolean(), and .nullable() query fields. Query arrays and object unions use the same query transport rules as page URLs. Singleton values in array-valued records remain arrays. Object-union branches normalize independently; use a string-literal discriminator when scalar and singleton-array inputs would otherwise be ambiguous.

    API paths follow the same portable route grammar as pages: optional parameters are terminal, and constraints reject anchors, alternation, lookarounds, empty matches, and nonterminal slash-spanning patterns.

    Use .returns<Type>() only on contracts without a response schema when compile-time response typing is sufficient. A response schema owns its input and output types; calling .returns<Type>() on it is a type error and throws for JavaScript callers. Prefer a Zod response when external data should be checked at runtime.

    Conventional routes live at src/features/<feature>/api/<action>/route.ts and export exactly one lower-camel runtime value named *ApiRoute, such as fetchBookingApiRoute.

    Keep that layout flat: doctor and build diagnose nested or misplaced route modules. An isolated route test does not prove discovery or registration. Node and generated HTTP Lambda production builds initialize the assembled application to catch registration conflicts without dispatching requests or resolving request-time environment providers. Cloudflare needs separate Worker-runtime validation; see deployment build behavior.

    Implement the server route

    #

    saveProfile and rateLimitMiddleware below are application dependencies. Configure authentication before enabling auth: true, and authorize access to the requested profile in your application; a valid session alone does not establish ownership.

    src/features/profile/api/updateProfile/route.ts
    import { createApiRoute } from "#brix/server";
    import { updateProfileApiContract } from "./contract.ts";
    
    export const updateProfileApiRoute = createApiRoute(updateProfileApiContract, {
      auth: true,
      middleware: [rateLimitMiddleware],
      handler: async (_c, { body, params }) => {
        const profile = await saveProfile(params.profileId, body);
        return { id: profile.id, displayName: profile.displayName };
      },
    });
    

    With authentication and authorization in place, POST /api/profiles/profile-123 with {"displayName":"Ada"} returns the saved { id, displayName } JSON object. Return plain JSON data; Brix normalizes, validates, and responds. undefined produces 204. Invalid successful output and unexpected failures reach the application's error policy, which returns a generic JSON 500 by default. A deliberate Hono HTTPException (from brix/hono/http-exception) passes through: one constructed with res returns that response, and one with only a status and message returns JSON { "error": message } with that status, like framework 400, 413, and 415 failures. Authenticated responses without their own Cache-Control header, including authentication failures, receive Cache-Control: private.

    Besides handler, route options are auth, middleware (Hono middleware that runs after authentication), maxBodyBytes (see request size), openapi (operation documentation; see API documentation), and enabled. A route with enabled: false is not mounted and is left out of the production manifest and OpenAPI document.

    A wildcard path such as /files/* passes the decoded tail as params["*"], so an encoded slash (%2F) in the request becomes /. Validate wildcard values as paths and never treat them as already-sanitized file names.

    Routes are discovered automatically. Do not mount them manually or import route.ts into browser code. Server code can call route.execute(c, options) directly without HTTP or middleware; auth context and input/output types remain checked. This does not rerun authentication, rate limiting, or middleware-owned authorization. Use it only with an already appropriate context and enforce any resource-level permissions in shared application logic.

    Direct execution returns Promise<T> and rejects with an ordinary Error on query, body, or response validation failures (never an HTTPException), or with the handler's own error, unlike the ResultPromise returned by HTTP clients and hooks. Required query input remains required, including unions whose branches require different keys. Paths with only optional parameters permit omission of params; handlers receive an empty params object when no values are supplied.

    Test the handler and invalid input through the route harness, then continue with calling API contracts.

    JSON body media types

    #

    JSON-body routes accept application/json and application/*+json media types, case-insensitively. Parameters such as charset=UTF-8 or a vendor profile are ignored; parsing uses Fetch's UTF-8 JSON decoder, not charset-based transcoding. A nonempty body without Content-Type returns 415: browsers can send such a body cross-origin without a CORS preflight, so Brix never parses it as JSON. A missing Content-Type is accepted only for a zero-length body. An explicitly empty or incompatible media type, including text/plain, returns 415 before parsing. Malformed JSON and schema failures return 400. Authentication and route middleware run first. Bodyless contracts and direct .execute calls do not check HTTP media types.

    A body or query transform that throws, such as z.string().transform((value) => new URL(value)) receiving an invalid URL, also returns 400 (Invalid request body or Invalid query parameters) without exposing the thrown message; a deliberate HTTPException thrown there keeps its status. Request schemas must be synchronous: an async refinement or transform fails every request with a 500 whose cause names the schema, so validate asynchronously in the handler instead. Direct .execute reports the same input failures as ordinary errors with the original failure as cause.

    A missing or zero-length JSON body is validated as undefined, matching direct .execute calls and Brix clients that omit an undefined body. Use a body schema that accepts undefined, such as z.object({ count: z.number() }).optional(), to allow absence; schema defaults and transforms apply normally. Required body schemas still return 400 for absence. Whitespace-only and malformed nonempty JSON return 400 rather than becoming undefined; JSON null is a distinct value and must be accepted by the schema explicitly. Media-type checks still apply even when the body is absent. These absence semantics do not change URL-encoded form parsing.

    Authentication and other middleware run before body validation. If middleware inspects the body, read it with await c.req.arrayBuffer() before any c.req.text() or c.req.json() call, and never consume c.req.raw directly. Brix distinguishes an empty body from a nonempty one using the original bytes from Hono's body cache. Reading text first is lossy: Fetch's decoder strips a UTF-8 byte-order mark, so a BOM-only body would later look empty and validate as undefined instead of returning 400.

    Send Content-Type: application/json from custom clients. Brix clients set it by default and retain explicit vendor JSON types. testApi sets JSON content type itself; use raw application requests for missing/wrong media-type cases. Media-type checks are not authorization; see request size and cross-origin protection for the framework defaults that bound bodies and reject cross-origin browser mutations.

    Request size and cross-origin protection

    #

    Body-schema API routes and every response route reject request bodies larger than 1 MiB (1,048,576 bytes) with 413 and JSON { "error": "Request too large" }. On API routes the check runs before authentication, middleware, or parsing: a declared Content-Length is checked without reading the body, and a chunked body is buffered only up to the limit. Response routes check a declared Content-Length at the same point but never buffer a chunked body; the limit applies as the handler reads it (see response routes). Change the application default with defineBrixServer(brix, { maxBodyBytes }) and a single route with maxBodyBytes in its options:

    export const importCatalogApiRoute = createApiRoute(importCatalogApiContract, {
      auth: true,
      maxBodyBytes: 8 * 1024 * 1024,
      handler: async (_c, { body }) => importCatalog(body),
    });
    

    Values must be non-negative safe integers; invalid values fail at definition or route creation. Bodyless API routes do not read the request body and are not limited.

    createBrixApp also rejects unsafe-method (POST, PUT, PATCH, DELETE) browser requests that are not same-origin, with 403, Cache-Control: no-store, and JSON { "error": "Forbidden" }, before route matching. Requests whose Sec-Fetch-Site is same-origin or none pass. cross-site and same-site requests are rejected unless their Origin is listed in csrf.trustedOrigins. Without Fetch metadata, a request without Origin passes (non-browser clients, webhooks, and server-to-server calls), and an Origin whose host matches the request host passes. GET, HEAD, and OPTIONS are never blocked, so keep those methods free of side effects.

    export const brixServer = defineBrixServer(brix, {
      csrf: { trustedOrigins: ["https://admin.example.com"] },
    });
    

    Trusted origins must be exact http or https origins without paths or wildcards. A separately hosted frontend that calls the API cross-origin with credentials must be listed here as well as in its CORS policy. csrf: { exemptPaths: ["/token"] } exempts exact paths, compared with the path as received, for endpoints that read no cookies and accept requests from any site, such as an OAuth token endpoint; see protect mutations from other sites. csrf: false disables the guard only when a trusted upstream enforces an equivalent policy. The guard rejects other origins, including sibling subdomains; add session-bound tokens only for flows that must also resist script on your own origin or browsers that send neither Sec-Fetch-Site nor Origin.

    URL-encoded form bodies

    #

    Use this alternative when an endpoint expects form encoding, such as an OAuth token service. The profile example above uses default JSON encoding. Declare bodyEncoding: "form-urlencoded" for flat form input with JSON output:

    export const exchangeTokenApiContract = createApiContract({
      method: "POST",
      path: "/token",
      bodyEncoding: "form-urlencoded",
      body: z.object({
        grant_type: z.literal("authorization_code"),
        code: z.string(),
        redirect_uri: z.string(),
        code_verifier: z.string().optional(),
      }),
      response: z.object({ access_token: z.string(), token_type: z.string() }),
    });
    

    Schema input must be a flat object of strings or optional strings. Numbers, booleans, nulls, nested objects, arrays, and unconstrained unknown/any inputs are rejected by the contract types. String-first transforms such as z.string().transform(Number) are supported: transport sends the original string and handlers receive parsed output. Defaults are applied when parsing, not while sending. GET and bodyless contracts cannot declare an encoding.

    Callers pass plain objects, not URLSearchParams or FormData. Encoding uses standard UTF-8 form rules: spaces become +, literal plus signs become %2B, empty strings remain present, and undefined fields are omitted. Incoming duplicate decoded names return 400, even if values match. Percent escapes follow the platform's forgiving URLSearchParams decoding. No array or nested-object syntax is inferred.

    Mounted form routes require application/x-www-form-urlencoded, with an optional UTF-8 charset; missing or incompatible content types return 415. Invalid form bodies and schema failures return 400. Auth and middleware run before parsing. Unlike JSON routes, form routes require an explicit content type. Direct .execute normalizes form input through the same wire rules before applying the schema once; output remains JSON.

    Form routes use the same body limit and cross-origin guard as JSON routes. CORS and content-type checks are not authorization. Signed requests needing original bytes remain application-owned response routes; form parsing cannot replace raw signature verification.

    Form encoding does not provide native HTML error UX. For a form that also works without JavaScript, use a separate native POST presentation of the same update operation, with explicit 303 redirects and session-scoped receipts. Keep expected validation failures as outcome data; do not introduce a JSON-or-redirect API response contract.