Skip to content
brix.v2.15.0+b120c49

Search documentation

Loading search…

    Documentation menu
    Docs / Getting startedRead Markdown
    On this page

    Project Structure

    Brix applications organize product code by feature while reserving a few top-level files for browser-safe and server-only framework wiring.

    A typical application

    #
    src/
      app.ts                  # application entry: createBrixApp(brixServer)
      brix.ts                 # browser-safe contract and URL factories (#brix)
      brix.server.ts          # server route factories and integrations (#brix/server)
      env.server.ts           # request environment declaration (#brix/env)
      env.script.ts           # explicit loading for scripts (#brix/env/script)
      env.generated.d.ts      # generated from env/.env.schema
      test/
        harness.ts            # project route harness (#brix/test)
      features/
        booking/
          api/
            fetchBooking/
              contract.ts
              route.ts
              route.test.ts
          pages/
            bookingDetails/
              contract.ts
              Page.tsx
              route.ts
              route.test.ts
          responses/
            downloadReceipt/
              contract.ts
              route.ts
              route.test.ts
          components/
            BookingCard.tsx
            BookingSummary.tsx
            bookingSummary.fragment.ts
          BookingActions.tsx      # "use island" component
          booking.store.ts
    env/
      .env.schema
      .env.development
      .env.test-run
      .env.production
      .env.local
    panda.config.ts           # optional Panda configuration
    vite.config.ts
    tsconfig.json
    oxfmt.config.mts
    oxlint.config.mts
    package.json
    

    Keep tests beside the code they exercise. Features can also contain schemas and domain modules in descriptive local directories. Generated Panda utilities are written to the ignored styled-system/ directory; do not edit or commit them.

    Framework wiring

    #

    src/brix.ts is browser-safe and defines project-bound contract and URL factories:

    import { defineBrix } from "brix/contracts";
    
    export const brix = defineBrix();
    export const {
      createApiContract,
      createMarkdownIndexContract,
      createPageContract,
      createResponseContract,
      executeApi,
      getMarkdownIndexPath,
      getPath,
    } = brix;
    

    src/brix.server.ts is the server boundary:

    "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;
    

    The shared src/test/harness.ts binding exports the route-test helpers from createTestHarness:

    import { createTestHarness } from "brix/test";
    import { createBrixApp } from "brix/server";
    import { brixServer } from "#brix/server";
    import type { CoercedEnvSchema } from "#/env.generated.d.ts";
    
    export const { testApi, testFragment, testPage, testResponse, withOptions } = createTestHarness({
      createApp: () => createBrixApp(brixServer),
      env: { STAGE: "test-run", VERSION: "test" } satisfies CoercedEnvSchema,
    });
    

    These files configure your application; keep their exports aligned with the canonical setup above. Generators import these bindings rather than creating a second configuration. Before writing, a generator checks that the bindings it needs exist (for example createPageContract, createPageRoute, and testPage for a page) and reports a missing one without writing a partial slice. Restore that export while preserving your existing application configuration.

    The authored env/.env.schema owns configuration validation. env.generated.d.ts is generated and committed; env.server.ts declares request configuration without loading it, and env.script.ts provides explicit loading for scripts. Keep personal values in ignored env/.env.overrides, not in committed .env.local. See environment schemas.

    src/app.ts should stay infrastructure-only:

    import { createBrixApp } from "brix/server";
    import { brixServer } from "./brix.server.ts";
    
    export const app = createBrixApp(brixServer);
    

    The server entry, src/app.ts or the module named by defineBrixConfig({ server }), must construct the app it exports. Development reloads routes by re-evaluating that module; re-exporting an instance created in another module fails with an error naming the entry instead of serving stale routes.

    Feature route conventions

    #

    Brix discovers server modules by location and export name:

    • page routes: src/features/<feature>/pages/<name>/route.ts, exporting one *PageRoute
    • JSON API routes: src/features/<feature>/api/<name>/route.ts, exporting one *ApiRoute
    • native response routes: src/features/<feature>/responses/<name>/route.ts, exporting one *ResponseRoute
    • Markdown index routes: src/features/<feature>/markdown-indexes/<name>/route.ts, exporting one *MarkdownIndexRoute
    • HTML fragments: any <name>.fragment.ts sidecar under src/features/, exporting one PascalCase *Fragment

    The contract.ts beside an API, page, or response route exports exactly one lower-camel runtime value ending in ApiContract, PageContract, or ResponseContract. Doctor rejects any other runtime export there, so put shared request and response schemas in a separate module, such as schemas.ts, and import them into the contract. Type-only exports are allowed. Markdown index contracts are declared inside their route.ts.

    Route export names are lower camel case, such as bookingDetailsPageRoute; BookingDetailsPageRoute is rejected. The exported value must come from the factory that matches its location (createPageRoute, createApiRoute, createResponseRoute, createMarkdownIndexRoute, or createFragment), and each route value is discovered from exactly one module: re-exporting a route from a second route.ts fails before the server starts. A page's Page.tsx exports exactly one named runtime component ending in Page. Type-only exports are allowed everywhere. Route modules and fragment sidecars cannot use export * or export * as name re-exports, which produce module namespaces rather than routes; re-export the binding by name instead. Islands need no fixed location: any PascalCase-named module under src/, such as BookingActions.tsx, that starts with a "use island" directive and exports exactly one PascalCase component is discovered; see islands.

    Route modules are always named route.ts, and fragment sidecars .fragment.ts; doctor reports a route.tsx or .fragment.tsx file with the rename to make. The route directory is flat: moving api/fetchBooking to api/admin/fetchBooking is unsupported, and route.ts is reserved for route modules. Doctor and the build reject misplaced route.ts files instead of silently dropping them; move the complete slice to a supported <feature>/<category>/<name> path and repair its imports. A passing isolated route test does not prove discovery. Feature directories named test are discovered like any other feature.

    Generate a correctly shaped slice instead of assembling it by hand. Route, store, and feature names are camelCase; island names are PascalCase:

    brix add page bookingDetails --feature booking
    brix add api fetchBooking --feature booking
    brix add response downloadReceipt --feature booking
    brix add fragment bookingSummary --feature booking
    brix add island BookingActions --feature booking
    brix add store booking --feature booking
    

    Each generator writes the module and a colocated test. Fragments go under the feature's components/ directory; islands and stores go at the feature root.

    Imports and boundaries

    #

    Generated applications provide aliases for deliberate boundaries:

    import { createPageContract } from "#brix";
    import { createPageRoute } from "#brix/server";
    import { testPage } from "#brix/test";
    import { BookingCard } from "#/features/booking/components/BookingCard.tsx";
    

    Use ./ within one directory and #/ across feature directories. Do not import server modules into browser-safe contracts or islands. Import framework-owned dependencies through Brix facades such as brix/zod and brix/hooks.

    Contracts describe browser-safe inputs, outputs, and URLs. Route modules implement those contracts on the server. A page's Page.tsx renders its loaded data; an island opts a component subtree into browser execution. Follow that separation when deciding where a module belongs: database clients, credentials, and request-only services must not enter an island's import graph, even indirectly.

    Managed Panda styling

    #

    Brix includes native Panda 2 in full-stack UI applications. Import generated utilities from #brix/panda/css, mapped to styled-system/css/index.js. Author optional root panda.config.ts with a default definePandaConfig export from brix/panda. Brix connects native extraction, transforms, generated types, and stylesheet injection; no separate installation or PostCSS is needed.

    Remove the obsolete panda option from defineBrixConfig; even panda: true is rejected. Customize native Panda instead, for example preflight: false in panda.config.ts when the application already owns a CSS reset. Styled libraries and managed Storybook use the same native styling system. Plain libraries without a Panda config, custom Lambda handlers, and browser-only React builds do not gain a CSS pipeline.

    Source-style edits use native CSS HMR. Added/deleted files update extraction. Config or imported-token edits rebuild utilities and reload the page, resetting island state. Published libraries use explicit designSystem composition; see styling.

    Island edits use Preact Fast Refresh and preserve compatible hook state. Changes to server-rendered pages or routes outside an island boundary intentionally reload the page. Production builds still extract the complete application stylesheet.

    Tool configuration

    #

    Standalone projects own .node-version, oxfmt.config.mts, and oxlint.config.mts. Workspace members inherit those files and Git hooks from the workspace root; do not copy generated defaults into every member. Prefer root-relative overrides for member-specific formatting or lint policy. See linting and formatting for managed defaults and configuration.

    The generated vite.config.ts composes the supported application build:

    import { defineBrixConfig } from "brix/vite";
    
    export default defineBrixConfig();
    

    For full-stack applications, Brix manages Vite's asset base: / in development and ./ in production, preserving relative chunk URLs and request-specific asset delivery. Authored vite.base is rejected, whether supplied in an object or returned from a callback. Set the top-level assetPrefix option to change generated asset URLs to a local prefix or an absolute HTTP(S) CDN URL. The prefix must name a dedicated path such as /_brix/; / and a bare CDN origin are rejected because the asset handler would capture every route. assetOutDir (default dist/_brix) must be a directory inside dist that does not overlap server or deployment output: dist/assets, dist/deployment, dist/fastly, and the server entry files are reserved, in any letter case because macOS and Windows filesystems are case-insensitive by default. For request-specific delivery, use server renderer.assetPrefix; see server foundations. Neither option changes page or API route paths. The separate React defineBrixReactConfig() pipeline still supports vite.base; see managed React applications.

    The vite escape hatch is an allowlist: define, resolve (except jsxImportSource), server, publicDir, build.minify and build.sourcemap, ssr.external, ssr.noExternal, ssr.optimizeDeps, ssr.resolve, environments.ssr.resolve, and project plugins. Brix rejects every other option, including css, optimizeDeps, build.target, envDir, and root, along with plugins whose names start with the reserved brix: prefix. Project plugins, define, and resolve also apply to the managed node and browser test projects, so plugin-provided virtual modules and transformed imports resolve under brix test. In development the SSR runner externalizes packages resolved inside node_modules; linked workspace packages resolved outside it stay in Vite's module graph, so rebuilt library output reaches SSR without a restart. Explicit noExternal lists still apply; noExternal: true takes effect only in production builds.

    Brix owns the build targets. Production island JavaScript and CSS target Vite's baseline-widely-available browsers (Chrome and Edge 111, Firefox 114, Safari 16.4) on every platform, while the server bundle targets Node 24 for node and lambda and ES2022 for Cloudflare and Fastly workers.

    Use brix check to validate structure, imports, exports, formatting, lint, and types; brix inspect routes lists the routes discovery found. Continue with pages, API routes, and islands.