Skip to content
brix.v2.15.0+b120c49

Search documentation

Loading search…

    Documentation menu
    Docs / APIs and dataRead Markdown
    On this page

    Native response routes

    Use response routes for redirects, downloads, streams, non-JSON responses, or application-owned request processing. Construct responses with the request context's typed helpers. For schema-owned JSON or flat URL-encoded request bodies with JSON output, use API contracts instead. Multipart input and raw signed payloads remain application-owned.

    Create the contract and route

    #

    Project bindings must export createResponseContract from brix in src/brix.ts, createResponseRoute from brixServer in src/brix.server.ts, and testResponse from createTestHarness in src/test/harness.ts. These are the canonical bindings used by the generator; see project structure. Then generate the conventional files:

    brix add response beginLogin --feature account
    

    This creates contract.ts, route.ts, and route.test.ts in src/features/account/responses/beginLogin/. Keep the contract separate; response routes have no inline contract form. contract.ts exports exactly one runtime value, the *ResponseContract, so shared schemas belong in another module.

    src/features/account/responses/beginLogin/contract.ts
    import { createResponseContract } from "#brix";
    import { z } from "brix/zod";
    
    export const beginLoginResponseContract = createResponseContract({
      method: "GET",
      path: "/auth/login",
      query: z.object({ destination: z.enum(["account", "reports"]).default("account") }),
    });
    
    src/features/account/responses/beginLogin/route.ts
    import { createResponseRoute } from "#brix/server";
    import { beginLoginResponseContract } from "./contract.ts";
    
    export const beginLoginResponseRoute = createResponseRoute(beginLoginResponseContract, {
      auth: false,
      handler: (c, { query }) => {
        const returnTo = query.destination === "reports" ? "/reports" : "/account";
        c.header("Cache-Control", "no-store");
        return c.redirect(`/oauth/start?returnTo=${encodeURIComponent(returnTo)}`);
      },
    });
    

    Contracts support GET, POST, PUT, PATCH, and DELETE, a string path, and an optional Zod query schema. Path parameters are inferred. Callers of getPath provide query schema input; required query keys make the options/query input required. URL generation serializes input directly—it does not apply Zod transforms or defaults. The server validates and gives the handler parsed query output.

    Query fields must accept URL strings (z.coerce.number(), z.stringbool()), and record arrays and object unions follow the shared query transport rules, including singleton arrays and branch-specific normalization. Use string-literal discriminators when scalar and singleton-array branches would otherwise be ambiguous.

    The route accepts auth (true or false; any other value throws at creation), maxBodyBytes, middleware, and enabled. Its handler returns a response from c.body, c.text, c.json, or c.redirect, synchronously or asynchronously. These helpers incorporate prepared context headers and cookies, including the request ID; Brix preserves the response without buffering or rebuilding it. There is deliberately no body schema: read c.req.raw using native request APIs and own content-type and validation policy in the application. Request bodies are still limited: 1 MiB by default, or the application's or route's maxBodyBytes. A declared Content-Length above the limit returns 413 JSON { "error": "Request too large" } before locale checks, authentication, or middleware run. A body without a declared length (a chunked or streamed upload) is never read or buffered before the handler; Brix counts bytes as the application reads them, and a read that passes the limit fails with an HTTPException(413). Once the limit has been passed, the route responds with the same 413 JSON whatever the handler returns, even if it caught the read error or the runtime or fetch() wrapped it in another error. If the error propagates, a custom onError receives it like any other HTTPException, and Brix then replaces that error response with the 413 JSON. Bytes read before the limit was crossed have already reached the application, so stream to a temporary destination and commit only after the read completes.

    Use c.body for bytes, streams, already-produced HTML/XML, or an empty response, setting the appropriate content type:

    handler: (c) => c.body("<receipt />", 200, { "Content-Type": "application/xml" });
    

    HEAD requests run the GET pipeline but return no body, retaining its status and headers, including an explicitly supplied Content-Length. At the createBrixApp response boundary, Brix requests cancellation of the final discarded body, including responses returned by application middleware. It does not read or buffer the stream, wait for cancellation, or turn cancellation rejection into an HTTP error. Stream producers should release resources in cancel; return an unlocked stream so cancellation can reach the producer. Normal GET streams remain unconsumed and caller-owned.

    TypeScript rejects raw new Response, Response.redirect, Response.json, fetched responses, and helpers annotated to return only Response. Let helper return types infer rather than erasing their typed response information. c.html, c.newResponse, and c.notFound also return untyped responses and are not supported here: use c.body for custom content, c.text("Not Found", 404) for a text 404, and page routes for Brix-rendered HTML. This is a compile-time API rule, not a runtime security boundary; assertions or unchecked JavaScript can bypass it. The runtime guard rejects non-response values.

    A route module lives at src/features/<feature>/responses/<name>/route.ts and exports exactly one lower-camel runtime value ending in ResponseRoute, such as beginLoginResponseRoute; contracts end in ResponseContract. Brix discovers and mounts it automatically, just like a page or API route.

    Browser code imports only the contract and uses getPath(beginLoginResponseContract, { query: { destination: "reports" } }). The same helper builds API and page URLs. It constructs an address, not an HTTP request: an anchor always uses GET, regardless of a contract's method.

    Boundaries and errors

    #

    Response contracts do not have response schemas, .execute, executeApi/useApi support, contract mocks, or OpenAPI operations. Use native fetch when calling one. getPath is available for URL construction; unlike pages, response contracts do not accept locale maps or Markdown representations.

    Invalid query input returns 400 with JSON { "error": "Invalid query parameters: …" } under the default error policy. Unexpected failures use the configured server error policy, whose default is a generic JSON 500. Authentication and middleware run before query validation and the handler.

    Redirect destinations are security-sensitive. For OAuth and return URLs, use fixed or allowlisted destinations; never reflect an untrusted URL. Authentication/private download responses should normally set Cache-Control: no-store. Response routes have no Brix edge-cache policy. That does not automatically add an HTTP no-store header: set the header explicitly, as in the login example.

    Normal JSON APIs should report authentication failures with 401/403 rather than redirects. Page loaders may still redirect when handling real browser page navigation.

    Progressively enhanced mutation forms

    #

    Use two presentations of one application-owned update operation: an API route returns JSON for useApi, while a native response route handles the ordinary form POST and returns an explicit 303 redirect. Do not make an API contract alternate between JSON and HTML or redirects.

    This is an implementation checklist, not a deployable authentication, receipt, or replay recipe. Brix supplies the route and client APIs; your application must supply the production policies below before exposing a mutation. In-memory maps and simulated login are not suitable substitutes, including in a multi-instance deployment.

    1. Generate an API route and a response route in the same feature. Keep browser-safe contracts separate from the server-only update operation. Use getPath for the form action targeting the response contract and method="post"; the API contract is only the enhanced target.
    2. Authenticate and authorize both mutation paths. Enforce a streamed byte limit before parsing, an allowed content type/charset, and a field-count/length policy. Do not trust Content-Length alone. Reject duplicate singleton names, including encoded aliases, rather than silently selecting the first or last value. Native response routes own their decoding; API form bodies follow the flat-string encoding rules.
    3. Keep expected field and business validation inside the shared operation. Accept transport-valid strings, then return an outcome containing submitted values, field errors, a form error, and an explicit saved discriminator. A transport schema that rejects an ordinary invalid email before the operation runs cannot return your retained-value outcome. Authentication, malformed transport, and unexpected server failures remain separate failures.
    4. Return that outcome as schema-validated JSON from the API route. An HTTP 200 or successful Result means the request succeeded, not necessarily that the mutation saved. Only after the saved outcome, explicitly invalidate affected cached reads; see clients. If server-side data is cached too, invalidate it in the server operation for both presentations. Report invalidation failure separately from mutation failure: do not invite another write merely because refreshing the displayed read failed.
    5. For native submissions, persist the outcome under an opaque, unpredictable, session-scoped receipt. Redirect to a fixed local page with only that receipt identifier, using c.redirect(receiptUrl, 303). Do this for expected validation errors as well as success. The GET must check receipt ownership and expiry before rendering retained values and errors. Set Cache-Control: no-store on POST and personalized GET responses and exclude them from shared edge caches. Do not put submitted values or CSRF tokens in redirect URLs or logs.
    6. Render the native form first, then enhance its submit event with useApi. Preserve named controls, labels, and hidden CSRF/submission fields. Snapshot values before starting a request, clear stale success/errors, announce pending state, and guard repeated submit events. Define whether inputs are locked or edits made during the request survive its response. Retain input on expected errors; associate field errors with aria-invalid and aria-describedby and focus a keyboard-reachable error summary after enhanced failure. Provide an equivalent native GET error-focus policy. Do not use a success toast as the only outcome indication.

    Security, receipts, and uncertain outcomes

    #

    Cookie-authenticated forms need CSRF protection on both paths. createBrixApp already rejects cross-origin browser POSTs on both paths with 403, including Origin: null; keep that guard enabled and list only exact trusted origins. The guard already rejects sibling subdomains; add a session-bound token when a flow must also resist script on your own origin or browsers that send neither Sec-Fetch-Site nor Origin. SameSite cookies, CSP, disabled buttons, and JSON media checks do not replace these controls. See server security.

    Receipts retain presentation state; they are not idempotency records. Choose bounded storage, expiry, session revocation behavior, cleanup, and whether a receipt survives reload. A single-use flash receipt loses retained errors on reload. Missing/expired receipts need a safe recovery page, not another mutation. Use Secure/HttpOnly session cookies and the application's existing session service; never mint a login merely because someone visited the form page.

    A pending guard is UX, not duplicate-write prevention. To claim retry safety, atomically couple a durable, user/operation-scoped submission key and payload fingerprint with the mutation and its outcome. The same key and payload must replay the recorded outcome; changed payload must be rejected. Cover concurrent native/API requests and process failure after commit. Define retention and expired-key behavior before enabling retries; expiry must not silently turn an ambiguous retry into a new write. This transaction belongs to your database/service, not to a module-level map.

    Leave automatic POST retries disabled until that guarantee exists. A timeout, cancellation, or lost response does not prove the write failed. Retain the submitted snapshot and key during uncertainty; reconcile or retry the same payload under the application's replay policy before creating a new submission. Rotate the key after a known outcome. Do not silently resubmit changed values under an old key or claim exactly-once delivery from a browser guard.

    Acceptance checks before promotion

    #

    Run the built application with JavaScript enabled and disabled. Verify Enter submission, 303 then GET (including expected errors), reload without another write, retained Unicode/plus-sign values, field and form errors, error-summary focus and field links, a second save with no stale success, and pending state. Inspect a recording of actual keyboard/pointer interaction as well as assertions; screenshots alone do not establish keyboard behavior or screen-reader compatibility.

    Test anonymous and unauthorized users, wrong/missing tokens, foreign/missing/null Origin, another session's receipt, expired receipts, wrong media/charset, duplicate names, and streamed oversized bodies without a Content-Length. Assert that rejected submissions do not mutate. Exercise concurrent submissions across both routes, same-key changed payload, a response lost after commit, and the replay-expiry boundary. Assert write counts and outcomes, not merely response statuses. Verify that only a saved outcome refreshes cached reads, and that a failed refresh does not repeat the write.

    The route harness can check JSON and explicit redirect responses with testApi and testResponse; it cannot establish native browser navigation, hydration, focus, or durable transaction safety. Do not advertise those guarantees until the application's browser and persistence tests pass.

    Test native responses

    #

    Generated projects already export testResponse from src/test/harness.ts:

    export const { testApi, testFragment, testPage, testResponse, withOptions } = createTestHarness({
      createApp: () => createBrixApp(brixServer),
      env: { STAGE: "test-run", VERSION: "test" } satisfies CoercedEnvSchema,
    });
    

    Then exercise the route without following its redirect:

    src/features/account/responses/beginLogin/route.test.ts
    import { describe, expect, it } from "brix/test";
    import { testResponse } from "#brix/test";
    import { beginLoginResponseRoute } from "./route.ts";
    
    describe("beginLoginResponseRoute", () => {
      it("redirects to the OAuth start page", async () => {
        const response = await testResponse(beginLoginResponseRoute, {
          query: { destination: "account" },
        });
    
        expect(response.status).toBe(302);
        expect(response.headers.get("location")).toContain("/oauth/start");
      });
    });
    

    testResponse returns the native, unconsumed Response. Redirects are not followed and request bodies are not JSON-encoded. Options include params, query, native body: BodyInit, headers, cookies, locale, translations, and project-defined setup fields; contract-required path/query input remains required. Configure setupContext and env on createTestHarness, not individual requests. Read or stream the response body exactly once, or clone it first when multiple assertions need it.

    See route testing and server configuration for authentication, middleware, and error policy.