Skip to content
brix.v2.15.0+b120c49

Search documentation

Loading search…

    Documentation menu
    On this page

    Server foundations

    Define and assemble Brix's server boundary, connect caching, and prepare the generated application for deployment.

    These files are created by the full-stack application setup. Keep browser-safe contracts in src/brix.ts; put credentials, middleware, and server integrations in src/brix.server.ts. A managed React application has no Brix server—use a separate service when it needs one.

    Before continuing, run brix doctor from the application root and fix discovery errors. At the end, brix inspect routes should list your route modules and a focused route test should pass through createBrixApp without manually mounting them.

    Define and assemble the server

    #

    The generated server definition binds the validated environment and re-exports the route factories that feature modules import from #brix/server:

    src/brix.server.ts
    "use server";
    
    import { defineBrixServer } from "brix/server";
    import { brix } from "./brix.ts";
    import { env } from "./env.server.ts";
    
    export const brixServer = defineBrixServer(brix, { env });
    
    export const {
      createApiRoute,
      createFragment,
      createMarkdownIndexRoute,
      createPageRoute,
      createResponseRoute,
    } = brixServer;
    
    src/app.ts
    import { createBrixApp } from "brix/server";
    import { brixServer } from "./brix.server.ts";
    
    export const app = createBrixApp(brixServer);
    

    Passing env types c.env from your environment schema in every route, loader, and server option callback, and makes Brix parse the runtime environment before application code runs. Omit it only in an application without an environment schema; c.env is then an empty frozen object. See environment. Either way c.env replaces the platform's bindings object; read native bindings, such as Cloudflare KV or D1, with getPlatformBindings(c) from brix/server (see native Cloudflare bindings).

    createBrixApp owns Hono construction, request IDs, security and logging middleware, assets, rendering, and safe errors; see the request order. The generated production entry mounts discovered routes. Do not manually register conventional route modules.

    Server options

    #

    Every option is optional. Add them to the same defineBrixServer(brix, { env, ... }) call:

    • env: the validated environment, as above.
    • auth: the authentication middleware for routes with auth. See authentication.
    • csrf: trusted origins for the cross-origin mutation guard, or false. See cross-site protection.
    • maxBodyBytes: the default request body limit, 1 MiB (1_048_576) when omitted. Routes may override it.
    • security: secure-header and CSP overrides, or false. See secure defaults.
    • middleware: global application middleware, run in array order. See middleware.
    • renderData and renderer: browser-visible render data and production asset URLs.
    • notFound and onError: the public error contract. See errors.
    • logging and service: structured logs and service metadata. See logging.
    • dataCache and cachePolicies: native data caching and named edge cache hints, described below.
    • resolveLocale and translations: request locale and dictionaries. See translations.
    • openapi and versionHeader: the served API document and the X-App-Version header. See API documentation.
    • assets: false: disable built-in asset serving, described below.
    • integrations: server capabilities from integration subpaths, described below.

    Declare caching, do not implement it in routes

    #
    import { createMemoryDataCacheStore } from "brix/cache";
    
    export const brixServer = defineBrixServer(brix, {
      env,
      cachePolicies: ["publicPage", "sharedChrome"] as const,
      dataCache: { namespace: "booking", store: createMemoryDataCacheStore() },
    });
    

    dataCache owns native reuse of API and Contentful reads; brixServer.dataCache then supplies the public(...) and private(...) cache options. This memory store is local to one process. Choose a shared store when replicas must reuse or invalidate the same data. Pass a function (c) => config instead when the store depends on c.env; brixServer.dataCache(c) then returns the request's cache.

    Named cachePolicies are only edge hints that pages and fragments select by name. Names must be unique, start with a letter, and contain only letters, digits, ., _, and -. Omitted route policies are uncached, and Brix never stores edge responses itself. See caching and fragments.

    Locale-dependent responses must partition by a visible locale, whether locale resolution is used by translations or by application rendering alone. Localized paths are safe automatically; host-selected locale requires localePartition: "host"; cookie/header selection fails closed to uncached. See translations.

    Add server integrations

    #

    Integration subpaths export factories that return opaque BrixServerIntegration values. Pass them in integrations:

    import {
      createContentfulClientLoadingIntegration,
      createContentfulPreviewIntegration,
    } from "brix/contentful/server";
    
    export const brixServer = defineBrixServer(brix, {
      env,
      integrations: [
        createContentfulPreviewIntegration(previewOptions),
        createContentfulClientLoadingIntegration(loadingOptions),
      ],
    });
    

    Integrations mount their routes in array order, before discovered routes. The Contentful Preview and client-loading integrations work in either order. An integration may exempt its own route from the cross-origin mutation guard when it checks requests there itself, as the brix-auth integration does for its MCP endpoint. An integration may also handle requests before application middleware, after Brix's own guards: the brix-auth integration answers its MCP and metadata paths there. Each integration may appear once; duplicates and hand-written objects throw when the server is defined. The production entry also checks the build against them at startup. For example, contentfulPreview: true in vite.config.ts without createContentfulPreviewIntegration, or the integration without the build option, fails with a message naming the missing half.

    previewOptions and loadingOptions stand for the explicit options covered in Live Preview and client-introduced adapters. Client loading mounts same-origin routes that do not inherit page-route middleware, and getContentfulLoadingContext(c) from brix/contentful/server exposes the verified identity and scope to server services. Never serialize handler credentials or signing keys in render data.

    Select a production asset directory per request

    #

    Normally, generated scripts, stylesheets, and module preloads use the build's assetPrefix. For an alternate delivery location, set renderer.assetPrefix to a string or (c) => string. createBrixApp resolves it once per request and uses that value for production page and fragment assets and the default script/style CSP origins. Select from trusted configuration: the callback runs after environment loading and before application middleware.

    The value replaces the complete generated asset directory, including any build-added releases/<UUID>/ directory; it is not prepended to the existing URL. For example, a build URL /_brix/releases/abc/chunks/shared.js becomes https://cdn.example/app/v2/chunks/shared.js when renderer.assetPrefix is "https://cdn.example/app/v2/". Preserve release isolation by selecting a versioned destination and publishing the same build's files there with their relative layout intact. Omit the renderer override to retain the build's release URLs automatically.

    HTTP(S) URLs, root-relative paths, and request-relative paths are accepted, with an optional trailing slash. Request-relative paths resolve against the request URL; prefer root-relative or absolute URLs when pages and fragments have different paths. Credentials, query strings, fragments, and non-HTTP schemes are rejected. Generated chunk imports and generated asset references in CSS are relative to their delivered files. Immediate-island static imports remain preloaded; exclusively idle/lazy islands and dynamic imports do not become eager module preloads.

    This changes emitted URLs, not asset hosting. Configure the alternate server or CDN to serve those files, with CORS for cross-origin modules. assetOutDir, built-in asset serving, and deployment handoff URLs remain build-owned. Authored public URLs, Styling URLs, and arbitrary application URLs are not rewritten; this is not a signed-URL facility. Fonts and images on another origin need explicit CSP directives. Partition any HTML cache by the selected delivery location as well as its ordinary page and fragment dimensions. Development keeps Vite's asset URLs.

    References to files in public/ remain root-relative in built CSS and JavaScript, outside the generated release directory. Browser URL resolution still applies: CSS url('/image.svg') uses the stylesheet's origin, and new URL('/image.svg', import.meta.url) uses the module's origin. A string '/image.svg' assigned to an image in the document uses the page origin. When serving CSS or modules from a CDN, serve those public files at the CDN root too, or author an explicit application-origin URL.

    Built-in asset serving

    #

    Node production (brix start) serves the build's inventoried public/ files at root URLs such as /image.svg, alongside generated assets at the build prefix. It does not serve arbitrary files in dist/: the server bundle app.mjs and dynamic server chunks remain private, and build metadata (.vite/manifest.json, brix-island-manifest.json, and any other dot-segment path) is never served. The exclusion applies to the file a request resolves to, so a trailing slash, an encoded %2F, or a different letter case on a case-insensitive filesystem cannot reach it either; asset URLs ending in / are not served.

    • Generated assets named <name>.<hash>.<ext> (entries, chunks, and CSS/font assets) are cached immutably.
    • Public files use Cache-Control: public, max-age=0, must-revalidate, even for fingerprint-looking filenames.
    • Responses carry a weak ETag and answer a matching If-None-Match with 304.

    Before writing the Node server bundle, the build rejects public files that collide with any emitted server filename, including file/directory prefix collisions. Noncolliding files in public/assets/ are supported; the directory itself is not reserved. Rebuild to add public files and do not use symlinks in public/.

    Built-in assets are handled before discovered routes, so avoid URL collisions with application routes. Set assets: false to disable both public-file and generated-asset serving when external hosting delivers them instead.

    Deployment

    #

    For generated HTTP Lambda, configure defineBrixConfig({ platform: "lambda" }). brix build emits the complete generated handler in dist/app.mjs (app.handler); do not create a second source Lambda entry around src/app.ts.

    For a raw event handler or an application-owned Hono app, add handler: "src/handler.ts". It replaces HTTP assembly with a fully bundled Node dist/handler.mjs (handler.handler), without routes, islands, or Panda. See custom Lambda handlers.

    Brix exposes supported Hono facades: brix/hono, brix/hono/aws-lambda, brix/hono/cookie, brix/hono/cors, brix/hono/factory, and brix/hono/http-exception. Import Hono from these; do not add another Hono dependency. Verify server changes with brix doctor, brix inspect routes, focused tests, and brix build. See API routes, environment, and testing.

    Next, protect private routes in authentication and security, then add operational behavior in middleware and logging.