Skip to content
brix.v2.15.0+b120c49

Search documentation

Loading search…

    Documentation menu
    Docs / APIs and dataRead Markdown
    On this page

    API documentation

    Serve OpenAPI 3.1 and Swagger UI directly from the API contracts your application implements. No export command or separate route registry is needed. To generate clients for someone else's API, see OpenAPI client generation.

    Enable documentation

    #
    src/brix.server.ts
    "use server";
    
    import { defineBrixServer } from "brix/server";
    import { swaggerUi } from "brix/server/swagger-ui";
    import { brix } from "./brix.ts";
    import { env } from "./env.server.ts";
    
    export const brixServer = defineBrixServer(brix, {
      env,
      openapi: {
        info: { title: "Catalogue API" },
        ui: swaggerUi(),
      },
    });
    

    Brix serves GET /openapi.json in development and production and Swagger UI at /docs. Both are opt-in: omit openapi (or pass false) to disable the document, or omit ui to serve JSON alone. Swagger UI is opt-in by import as well: only brix/server/swagger-ui carries its roughly 2 MB of bundled scripts, styles, and licenses, so a server that never imports it does not ship them. That keeps edge bundles small, for example under Fastly's package and compiled-code limits. info.title is required. The document is assembled once, when the application mounts its enabled, discovered API routes; a route harness documents only the routes it mounted. It excludes disabled routes, standalone client contracts, pages, fragments, native response routes, manually mounted Hono routes, and documentation endpoints. It uses Cache-Control: no-store and an uncached API entry in the edge manifest. Global middleware, security headers, request IDs, and error handling apply as usual.

    Run brix dev, open /docs on your development server, and check that an implemented endpoint appears with the expected request and response shapes. Documentation is public by default, even when API routes require authentication. Add documentation middleware before deploying a private API reference. Swagger's request controls make real calls to the selected server; use test data when trying mutations.

    Application version

    #

    info.version defaults to the owning application's package.json version captured during development/build—not the Brix framework version or a workspace root version. An explicit info.version overrides only the document. Unmanaged and route-harness apps can supply static service.version instead; it is used as a release version only when it is a printable header value (ASCII without spaces or control characters), so a value such as 1.0 beta still appears in logs but not in X-App-Version. Without any of those sources, OpenAPI mounting fails with a configuration error. Request-derived service metadata is never used as a release version.

    When an application release version is available, Brix sends X-App-Version on its responses, including errors. An OpenAPI override does not change this header. Set versionHeader: false on defineBrixServer to disable automatic emission. A cached response carrying the header retains its producing release's version.

    Managed route handlers attach the version before any response-cache middleware stores the response. If your own handler or middleware returns a response before reaching a Brix route and caches it, set the header yourself; Brix cannot later recover which release produced a cached response that lacks it. Serialized render data is separate: its default version comes from resolved service.version, or "1", not the captured package version.

    Paths and Swagger UI

    #
    openapi: {
      info: { title: "Catalogue API" },
      path: "/api/schema.json",
      ui: swaggerUi({ path: "/reference" }),
    }
    

    swaggerUi() serves the UI at /docs; pass path to move it. The JSON and UI paths are independent literal absolute paths: segments may contain only letters, digits, ., _, ~, and -, and must differ from each other. Swagger automatically loads the configured document URL. Paths participate in route-collision checks; do not put public assets there, because asset serving precedes application routes.

    Brix serves scripts, styles, licenses, and the OAuth callback locally beneath the UI path. No CDN or remote validator is used. Scripts use the request CSP nonce; custom CSP must permit the local stylesheet and connections to documented API servers. Swagger authorization is not persisted in storage, and query parameters cannot override its configuration.

    OAuth popup authorization requires the browser to retain the opener while visiting a separate identity-provider origin and returning to the callback. Brix defaults Cross-Origin-Opener-Policy to same-origin-allow-popups for UI GET/HEAD responses and unsafe-none for callback GET/HEAD responses. Ordinary application routes, the JSON document, and assets retain same-origin.

    Swagger UI also fetches from the documentation page itself: authorization-code (including PKCE), password, and client-credentials flows POST to tokenUrl (and refreshUrl when refreshing), and openIdConnect schemes load openIdConnectUrl when the page opens. On UI GET/HEAD responses only, Brix adds the origins of absolute http:/https: tokenUrl, refreshUrl, and openIdConnectUrl values to connect-src, after your configured sources (or after default-src when you removed connect-src). Relative URLs are same-origin. The implicit flow needs no fetch. Other routes, the callback, and assets keep the application's policy unchanged, and contentSecurityPolicy: false adds nothing. The identity provider must still allow CORS requests from your documentation origin.

    Explicit security.crossOriginOpenerPolicy values and security: false take precedence. Setting same-origin explicitly prevents cross-origin popup authorization. If an edge emits security headers, preserve the scoped UI/callback policies there; the identity provider must also allow retaining the popup's opener. Register the callback URL beneath your configured UI path with the provider, for example /reference/oauth2-redirect.html.

    Independent documentation middleware

    #

    API authentication does not automatically protect documentation. Supply openapi.middleware for staff authentication, authorization, or other policies. It runs in order for JSON, UI, callback, and local assets, after the no-store policy. Normal global application middleware also applies.

    openapi: {
      info: { title: "Catalogue API" },
      middleware: [staffAuth.middleware, requireDocsAccess],
      ui: swaggerUi(),
    }
    

    Here staffAuth and requireDocsAccess are application-owned policies. To share API authentication, pass the server's auth.middleware explicitly. Omitted middleware leaves documentation public. Protected browser navigation needs browser-compatible credentials, such as a session cookie. Middleware presence is conservatively represented as a private boundary in the manifest; this is not a replacement for actual authorization.

    Server-only route documentation

    #
    import { createApiRoute } from "#brix/server";
    import { listProductsApiContract } from "./contract.ts";
    
    export const listProductsApiRoute = createApiRoute(listProductsApiContract, {
      openapi: {
        operationId: "listProducts",
        summary: "List published products",
        description: "Returns the current catalogue.",
        tags: ["Products"],
        response: {
          description: "Published products",
          items: {
            properties: {
              name: { description: "Display name", examples: ["Blue mug"] },
            },
          },
        },
      },
      handler: async () => [{ name: "Blue mug" }],
    });
    

    This example assumes the shared contract's response is z.array(z.object({ name: z.string() })). Contracts own method, path, and validation schemas; routes own optional operation and field documentation; server configuration owns the document and documentation endpoints. Route openapi supports operationId, summary, description, tags, deprecated, and security; other keys fail mounting.

    Without operationId, Brix derives one from the method and route source path, so moving the route file changes it. Set explicit IDs when clients or tooling depend on them. IDs may contain only letters, digits, ., _, and -, and must be unique.

    Add body, query, and response annotations for existing runtime schemas. Each node supports title, description, deprecated, and examples (an array of actual wire values, not named OpenAPI example objects). Use properties for object fields and items for homogeneous array elements. Property names and example shapes come from schema input types, including responses before client transforms: z.string().transform(Number) needs examples such as ["42"], not [42]. Optional and nullable wrappers retain field inference; a nullable node can include null as a whole-value example.

    Nested annotations are checked against the generated schema when routes mount with OpenAPI enabled. Unknown fields, missing schemas, structural or validation keywords such as type, required, minLength, $ref, and additionalProperties fail rather than overriding validation. Route annotations override descriptive Zod metadata only at their annotated occurrence; shared schemas and other routes remain unchanged. Example values receive TypeScript input-shape checking, not runtime validation of lengths, ranges, refinements, or transforms. Keep examples valid yourself.

    For recursive schemas, a root description stays on the root and a child description stays on that child. Unannotated grandchildren retain only shared Zod metadata; they do not inherit occurrence-specific annotations.

    Route examples must be plain JSON data: finite numbers, strings, booleans, null, dense arrays, and plain objects. Brix rejects undefined, functions, accessors, custom serialization, class instances and cyclic or excessively deep values rather than silently changing them during JSON serialization. The maximum container depth is 100, including the examples array. This serialization check does not validate examples against the contract schema.

    Unions support whole-value descriptions and examples, not branch field annotations or branch selectors. Nullable/optional single-shape wrappers are supported. Tuples support whole-value documentation, not items annotations. Recursive schemas support finite nested annotation trees; do not pass cyclic annotation objects. Dynamic record keys have no statically known generated property to annotate. Input typing cannot distinguish every Zod construction (for example structurally identical union branches), so generated-schema checks remain authoritative.

    For reusable server documentation, import ApiRouteOpenApiOptions<typeof contract> or ApiSchemaDocumentation<WireInput> as types from brix/server. No helper or browser stripping transform is needed: keep values in server-only route modules. Zod .describe()/.meta() remains an optional fallback and is browser-visible if shared; Brix does not strip it. Served documentation is not secret—protect its endpoints separately.

    Security descriptions and schema limits

    #

    Use securitySchemes and security to describe API authentication; they do not implement it:

    export const brixServer = defineBrixServer(brix, {
      env,
      auth,
      openapi: {
        info: { title: "Catalogue API" },
        middleware: [auth.middleware],
        securitySchemes: { session: { type: "apiKey", in: "cookie", name: "session" } },
        security: [{ session: [] }],
      },
    });
    

    Here auth is your defineBrixAuth policy, assumed to authenticate a cookie named session. Top-level security requirements apply only to routes with auth: true, which are also marked x-brix-auth: true; route-level openapi.security can describe other policies. An auth: true route without any security description produces a warning. Unknown scheme references fail. Without servers, OpenAPI's same-origin / default applies; configure trusted servers explicitly when needed, and never derive them from an untrusted request Host header.

    Schemas describe wire input, including JSON responses before transforms. Request body media types come from the contract: JSON by default, or application/x-www-form-urlencoded for bodyEncoding: "form-urlencoded". Form schemas document string input even when handlers receive transformed values; responses remain JSON. Encoding belongs in the contract, not in documentation annotations.

    Form bodies are always documented as required. A JSON body is required unless its schema accepts undefined, such as z.object({ ... }).optional(), matching the runtime's empty-body handling. The 204 response appears only when the route has no response schema or its schema accepts undefined; a required object response documents 200 alone. Routes with query or body schemas document Brix's 400 response, and body routes also document 413 and 415. These framework errors use the JSON shape { "error": string }.

    .returns<T>() provides no runtime schema and warns; response annotations require an actual schema and fail for .returns<T>() even though its TypeScript return shape exists. Apart from those framework input errors, Brix does not infer error responses or middleware changes to responses, headers, or cookies.

    Lossy cases warn once at mount as [Brix OpenAPI] console warnings: missing response schemas, custom refinements, catch fallbacks, coercion, and undescribed authentication. strict: true turns every warning into a mount failure. Unsupported schemas (for example dates, maps, sets, bigints, or transforms without an explicit input schema), wildcard or slash-spanning path parameters, duplicate operation IDs, and unsupported query serialization fail rather than publishing misleading documentation. An optional final path parameter produces two operations, one with and one without that segment; the second gets the operation ID suffix _without_<name>.

    Named query object schemas work with or without route annotations. Query fields must accept URL strings or repeated strings, as contract creation enforces. z.coerce.number() fields document their parsed number/integer type (with a coercion warning), while z.stringbool() and string-first transforms document string.

    Bigint and non-finite numeric literal members fail in both strict modes, including mixed literal sets. Undefined-only schemas such as z.literal(undefined) represent no JSON value, not arbitrary JSON or null; as responses, they document only 204. A mixed set such as z.literal([undefined, "ready"]) retains the JSON literal "ready" and the response's separate 204 path.

    Equivalent templated paths must use the same parameter names across all methods. GET /items/:id and POST /items/:id can share one path item; GET /items/:id and POST /items/:slug fail mounting because OpenAPI treats their templates as identical.