@bractjs/bractjs 0.1.28 → 0.1.29

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/package.json +3 -2
  2. package/src/__tests__/fixtures/app/routes/features-demo.tsx +28 -0
  3. package/src/__tests__/headers.test.ts +111 -0
  4. package/src/__tests__/integration.test.ts +34 -0
  5. package/src/__tests__/layout-registry.test.ts +7 -3
  6. package/src/__tests__/matcher.test.ts +29 -0
  7. package/src/__tests__/module-registry.test.ts +2 -3
  8. package/src/__tests__/route-lint.test.ts +5 -0
  9. package/src/__tests__/route-middleware.test.ts +84 -0
  10. package/src/__tests__/scanner.test.ts +46 -1
  11. package/src/__tests__/security-fixes.test.ts +201 -0
  12. package/src/__tests__/use-matches.test.ts +54 -0
  13. package/src/build/route-lint.ts +3 -3
  14. package/src/client/ClientRouter.tsx +118 -18
  15. package/src/client/hooks/useMatches.ts +32 -0
  16. package/src/client/router.tsx +7 -1
  17. package/src/client/rpc.ts +11 -1
  18. package/src/codegen/module-registry.ts +13 -21
  19. package/src/codegen/route-codegen.ts +8 -3
  20. package/src/config/load.ts +1 -0
  21. package/src/index.ts +11 -3
  22. package/src/server/action-handler.ts +1 -20
  23. package/src/server/adapter.ts +16 -0
  24. package/src/server/api-route.ts +47 -0
  25. package/src/server/csp.ts +9 -3
  26. package/src/server/csrf.ts +10 -3
  27. package/src/server/headers.ts +49 -0
  28. package/src/server/layout.ts +12 -19
  29. package/src/server/matcher.ts +29 -2
  30. package/src/server/matches.ts +50 -0
  31. package/src/server/middleware.ts +66 -0
  32. package/src/server/proto-guard.ts +56 -0
  33. package/src/server/render.ts +34 -16
  34. package/src/server/request-handler.ts +67 -27
  35. package/src/server/scanner.ts +45 -3
  36. package/src/server/search.ts +5 -1
  37. package/src/server/serve.ts +28 -3
  38. package/src/server/session.ts +12 -1
  39. package/src/server/validate.ts +4 -1
  40. package/src/shared/context.ts +3 -1
  41. package/src/shared/route-types.ts +108 -0
  42. package/types/config.d.ts +3 -0
  43. package/types/index.d.ts +17 -0
  44. package/types/route.d.ts +76 -1
  45. package/LICENSE +0 -21
  46. package/README.md +0 -1331
package/README.md DELETED
@@ -1,1331 +0,0 @@
1
- # BractJS
2
-
3
- [![npm version](https://img.shields.io/npm/v/@bractjs/bractjs)](https://www.npmjs.com/package/@bractjs/bractjs)
4
- [![license](https://img.shields.io/npm/l/@bractjs/bractjs)](LICENSE)
5
-
6
- > Production-grade SSR framework for **Bun + React 19**.
7
- > File-based routing · Parallel loaders · Streaming SSR · Built-in HMR · Server Actions · Typed routes · Single-binary deploy.
8
-
9
- ## Requirements
10
-
11
- - [Bun](https://bun.sh) ≥ 1.1 — no Node.js support
12
- - React 19 (peer dependency)
13
-
14
- This README is a **step-by-step guide to every function and feature** BractJS exports. Each section is self-contained and ordered from "first app" to "advanced". Every symbol shown here is a real export from `@bractjs/bractjs` (see [src/index.ts](src/index.ts)).
15
-
16
- ---
17
-
18
- ## Table of Contents
19
-
20
- 1. [Install & create an app](#1-install--create-an-app)
21
- 2. [Project structure](#2-project-structure)
22
- 3. [The root layout (`app/root.tsx`)](#3-the-root-layout-approotsx)
23
- 4. [File-based routing](#4-file-based-routing)
24
- 5. [Route module API: `loader`, `action`, `meta`, `beforeLoad`, `ErrorBoundary`, `default`](#5-route-module-api)
25
- 6. [Response helpers: `json`, `redirect`, `error`, `HttpError`](#6-response-helpers)
26
- 7. [Per-route context: `defineContext`](#7-per-route-context-definecontext)
27
- 8. [Streaming data: `defer`, `Deferred`, `isDeferred`, `<Await>`](#8-streaming-data)
28
- 9. [Client hooks](#9-client-hooks)
29
- 10. [Client components: `<Outlet>`, `<Link>`, `<Form>`, `<Scripts>`, `<LiveReload>`, `<Image>`](#10-client-components)
30
- 11. [Server Actions (`"use server"`) & client-only (`"use client"`)](#11-server-actions--client-components)
31
- 12. [Typed API routes: `route` + `createClient`](#12-typed-api-routes)
32
- 13. [Input validation: `validate`](#13-input-validation-validate)
33
- 14. [Middleware: `pipeline`, `requestLogger`, `cors`, `authGuard`, `csp`](#14-middleware)
34
- 15. [Sessions: `createCookieSession`](#15-sessions)
35
- 16. [Lifecycle hooks: `defineLifecycle`](#16-lifecycle-hooks)
36
- 17. [Environment variables & `*.server.ts`](#17-environment-variables)
37
- 18. [Typed routes](#18-typed-routes)
38
- 19. [Internationalization (i18n) utilities](#19-internationalization-utilities)
39
- 20. [Image optimization (`<Image>` + `/_image`)](#20-image-optimization)
40
- 21. [Build & run: CLI + programmatic API (`createDevServer`, `runBuild`, `loadUserConfig`)](#21-build--run)
41
- 22. [Single-binary deployment (`bun build --compile`)](#22-single-binary-deployment)
42
- 23. [Custom adapters (`BunAdapter`, Cloudflare)](#23-custom-adapters)
43
- 24. [Build plugins (for custom `Bun.build`)](#24-build-plugins)
44
- 25. [Configuration reference](#25-configuration-reference)
45
- 26. [Full export index](#26-full-export-index)
46
-
47
- ---
48
-
49
- ## 1. Install & create an app
50
-
51
- BractJS requires [Bun](https://bun.sh). There is no Node.js runtime path.
52
-
53
- ```sh
54
- # Scaffold a new app
55
- bunx bractjs new my-app
56
- cd my-app
57
-
58
- # Start the dev server (HMR on http://localhost:3000)
59
- bun run dev
60
- ```
61
-
62
- `bractjs new <name>` copies the scaffold template, runs `bun install`, and seeds `app/_generated/` so the single-binary entry typechecks before your first build.
63
-
64
- Add it to an existing project instead:
65
-
66
- ```sh
67
- bun add @bractjs/bractjs react react-dom
68
- ```
69
-
70
- `react` and `react-dom` v19 are **peer dependencies** — BractJS ships zero other runtime deps.
71
-
72
- ---
73
-
74
- ## 2. Project structure
75
-
76
- ```
77
- my-app/
78
- ├── app/
79
- │ ├── root.tsx # required — the <html> document shell
80
- │ ├── server.ts # single-binary entry (bun build --compile)
81
- │ ├── lifecycle.ts # optional — onStart / onShutdown / onError
82
- │ ├── route-types.gen.ts # generated by `bractjs codegen`
83
- │ ├── _generated/ # generated by `bractjs codegen:registry` / `:manifest`
84
- │ ├── actions.ts # "use server" actions (optional)
85
- │ └── routes/
86
- │ ├── _index.tsx # → /
87
- │ ├── about.tsx # → /about
88
- │ ├── blog/
89
- │ │ ├── layout.tsx # wraps /blog/*
90
- │ │ ├── _index.tsx # → /blog
91
- │ │ └── [id].tsx # → /blog/:id
92
- │ └── docs/
93
- │ └── [...slug].tsx # → /docs/* (catch-all)
94
- ├── public/ # static assets, served at /public/*
95
- ├── bractjs.config.ts # optional config (see §25)
96
- └── build/ # generated — do not edit
97
- ```
98
-
99
- Defaults: `appDir="./app"`, `publicDir="./public"`, `buildDir="./build"`, `port=3000`. All overridable (§25).
100
-
101
- ---
102
-
103
- ## 3. The root layout (`app/root.tsx`)
104
-
105
- **Required.** It provides the `<html>` document shell and is always rendered. Use the `<Outlet>`, `<Scripts>`, and `<LiveReload>` components from the package.
106
-
107
- ```tsx
108
- // app/root.tsx
109
- import { Outlet, Scripts, LiveReload } from "@bractjs/bractjs";
110
-
111
- export function meta() {
112
- return [
113
- { title: "My App" },
114
- { name: "viewport", content: "width=device-width, initial-scale=1" },
115
- ];
116
- }
117
-
118
- export default function Root() {
119
- return (
120
- <html lang="en">
121
- <head>
122
- <meta charSet="utf-8" />
123
- {/* BractJS hoists <title>/<meta> from every route's meta() into <head> */}
124
- </head>
125
- <body>
126
- <Outlet /> {/* renders the matched route tree */}
127
- <Scripts /> {/* injects the client bundle + bootstrap data */}
128
- <LiveReload /> {/* dev-only HMR client; no-op in production */}
129
- </body>
130
- </html>
131
- );
132
- }
133
- ```
134
-
135
- **Step by step:**
136
-
137
- 1. `export default function Root()` returns the full `<html>` document.
138
- 2. Put `<Outlet />` where the page content should render.
139
- 3. Put `<Scripts />` at the end of `<body>` — it's a marker the SSR pipeline replaces with the hashed client entry + `window.__BRACTJS_DATA__`.
140
- 4. `<LiveReload />` renders an HMR client script in dev and `null` in production.
141
- 5. Optionally `export function meta()` for site-wide defaults (route `meta()` overrides per descriptor).
142
-
143
- > `<title>`/`<meta>` tags from any route's `meta()` are rendered into `<head>` via React 19 document-metadata hoisting — you do not place them manually.
144
-
145
- ---
146
-
147
- ## 4. File-based routing
148
-
149
- Drop a file in `app/routes/`; it becomes a route. BractJS scans at startup and builds a trie.
150
-
151
- | File | URL |
152
- |------|-----|
153
- | `routes/_index.tsx` | `/` |
154
- | `routes/about.tsx` | `/about` |
155
- | `routes/blog/_index.tsx` | `/blog` |
156
- | `routes/blog/[id].tsx` | `/blog/:id` |
157
- | `routes/docs/[...slug].tsx` | `/docs/*` (catch-all) |
158
- | `routes/blog/layout.tsx` | wraps all `/blog/*` routes |
159
-
160
- - `[param]` → a dynamic segment, read via `useParams()` / `params` arg.
161
- - `[...name]` → a catch-all; the rest of the path lands in `params.name`.
162
- - `layout.tsx` in any directory wraps every route under it (layouts nest: `root → blog/layout → blog/[id]`).
163
- - Match priority per segment: **static > dynamic > catch-all**.
164
-
165
- No registration step — the file IS the route.
166
-
167
- ---
168
-
169
- ## 5. Route module API
170
-
171
- Every file in `app/routes/` (and `root.tsx`/`layout.tsx`) may export any combination of these. Import the arg types from the package.
172
-
173
- ```tsx
174
- import type { LoaderArgs, ActionArgs, MetaArgs } from "@bractjs/bractjs";
175
- import { redirect, json, HttpError } from "@bractjs/bractjs";
176
-
177
- // 1) loader — runs on every GET. Return value → useLoaderData().
178
- // `search` is the validated output of searchSchema (below), or the raw
179
- // string record when the route has no schema.
180
- export async function loader({ request, params, context, search }: LoaderArgs) {
181
- const post = await db.post.findById(params.id);
182
- if (!post) throw new HttpError(404, "Not found"); // → 404 page
183
- return { post };
184
- }
185
- export type LoaderData = Awaited<ReturnType<typeof loader>>;
186
-
187
- // 2) action — runs on POST / PUT / DELETE / PATCH. For one route handling
188
- // several buttons, compose it from `defineActions` (§5a) instead of a
189
- // hand-rolled `intent` switch.
190
- export async function action({ request, params, context, formData }: ActionArgs) {
191
- await db.post.update(params.id, { title: formData.get("title") as string });
192
- return redirect("/blog");
193
- }
194
-
195
- // 3) meta — SSR <title> / <meta>. Receives this route's loaderData slice.
196
- export function meta({ loaderData, params }: MetaArgs<LoaderData>) {
197
- return [
198
- { title: loaderData.post.title },
199
- { name: "description", content: loaderData.post.excerpt },
200
- { property: "og:title", content: loaderData.post.title },
201
- ];
202
- }
203
-
204
- // 4) beforeLoad — auth/redirect gate. Runs BEFORE loaders, on full-page GET
205
- // AND the /_data soft-nav endpoint. Return a Response to short-circuit.
206
- export function beforeLoad({ context, params, location }) {
207
- if (!context.user) {
208
- return redirect(`/login?next=${encodeURIComponent(location.pathname)}`);
209
- }
210
- }
211
-
212
- // 5) ErrorBoundary — renders when this segment's loader/component throws.
213
- export function ErrorBoundary({ error }: { error: unknown }) {
214
- return <p>Something broke: {error instanceof Error ? error.message : String(error)}</p>;
215
- }
216
-
217
- // 6) searchSchema — validate/coerce search params BEFORE loaders run (Zod,
218
- // Valibot, or anything with parse/safeParse). Failure → 400; use
219
- // .catch()/.default() per field for URLs that must tolerate junk.
220
- // Loaders receive the OUTPUT via `search`; the client reads it with
221
- // useSearch() — numbers stay numbers. (Typed end-to-end after codegen, §18.)
222
- export const searchSchema = z.object({
223
- page: z.coerce.number().int().positive().catch(1),
224
- q: z.string().optional(),
225
- });
226
-
227
- // 7) shouldRevalidate — veto automatic data refetches (the SWR background
228
- // refetch, and the revalidation after <Form>/fetcher mutations).
229
- export function shouldRevalidate({ currentUrl, nextUrl, formMethod, defaultShouldRevalidate }) {
230
- if (formMethod === "DELETE") return true; // always refetch after deletes
231
- return defaultShouldRevalidate;
232
- }
233
-
234
- // 8) ssr + Fallback — selective SSR (see also §21 for app-wide SPA mode):
235
- // true (default) full document SSR
236
- // "data-only" loaders run on the server; component renders client-only
237
- // false loader + component skipped during document SSR; the
238
- // client fetches /_data after hydration.
239
- // beforeLoad ALWAYS runs on the server — ssr:false is not an auth bypass.
240
- export const ssr = "data-only";
241
- export function Fallback() {
242
- return <p>Loading dashboard…</p>; // SSR'd in the component's place
243
- }
244
-
245
- // 9) default — the page component (required for a renderable route).
246
- export default function BlogPost() {
247
- const { post } = useLoaderData<LoaderData>();
248
- return <article><h1>{post.title}</h1></article>;
249
- }
250
- ```
251
-
252
- **Execution order for a request:**
253
-
254
- ```
255
- searchSchema → beforeLoad → (action, if mutating method) → loaders (root + layouts + route, in parallel) → render
256
- ```
257
-
258
- - **Loaders run concurrently** (root, every layout, and the route loader all in one `Promise.all`).
259
- - A loader that throws an `HttpError`/redirect `Response` is intentional control flow. Any *other* thrown error is caught, sanitized (generic message in production, full message+stack only when `NODE_ENV=development`), and rendered via the nearest `ErrorBoundary`.
260
-
261
- > **Security:** put auth checks in `beforeLoad` (per route) or middleware (cross-cutting) — never in a component. `/_data` (used by `<Link>` soft-nav) runs `beforeLoad` and the loader, so a component-only check would still leak loader JSON. See §14.
262
-
263
- ### Less boilerplate
264
-
265
- **Infer loader data — `useLoaderData<typeof loader>()`.** Pass the loader function type and the data type is inferred from its return (no `LoaderData` alias to maintain). The `Response` redirect branch is excluded; `Deferred` fields (from `defer()`, §8) are preserved for `<Await>`. Same for `useActionData<typeof action>()`.
266
- ```tsx
267
- export async function loader() { return { post: await db.post.find() }; }
268
- export default function Post() {
269
- const { post } = useLoaderData<typeof loader>(); // typed — no hand-written type
270
- }
271
- ```
272
-
273
- **Type search params on the args — `LoaderArgs<T>`.** Parameterize to drop the cast (the schema's output type):
274
- ```tsx
275
- export async function loader({ search }: LoaderArgs<{ page: number }>) {
276
- return db.posts({ page: search.page }); // search.page is a number
277
- }
278
- // After codegen (§18), `LoaderArgsFor<"/posts">` types params + context + search from the route.
279
- ```
280
-
281
- ### `defineActions` — multi-button forms without an `intent` switch
282
-
283
- A route action that handles several buttons usually devolves into `if (intent === …)`. `defineActions` composes it from one handler per intent, and `<Form intent="…">` (§10) renders the matching hidden input. An unknown/missing intent returns a 400 automatically (dev lists the known intents).
284
- ```tsx
285
- import { defineActions, safeValidate, formText } from "@bractjs/bractjs";
286
-
287
- export const action = defineActions({
288
- add: async ({ formData }) => {
289
- const r = await safeValidate(TitleSchema, formData); // §13
290
- if (!r.ok) return { error: r.firstError };
291
- addTodo(r.data.title); return {};
292
- },
293
- toggle: ({ formData }) => { toggleTodo(formText(formData, "id")); return {}; },
294
- delete: ({ formData }) => { deleteTodo(formText(formData, "id")); return {}; },
295
- });
296
- ```
297
- ```tsx
298
- <Form method="post" intent="toggle"><input type="hidden" name="id" value={id} /><button>Toggle</button></Form>
299
- ```
300
-
301
- ---
302
-
303
- ## 6. Response helpers
304
-
305
- Imported from `@bractjs/bractjs`.
306
-
307
- ```ts
308
- import { json, redirect, error, HttpError, isRedirect, isHttpError } from "@bractjs/bractjs";
309
- ```
310
-
311
- ### `json(data, init?)`
312
- Serialize a value as `application/json`.
313
- ```ts
314
- return json({ ok: true }, { status: 201 });
315
- ```
316
-
317
- ### `redirect(url, status?, headers?, options?)`
318
- Throw or return a redirect. **Open-redirect safe by default** — rejects `//evil.com`, `/\evil`, `https://…`, `javascript:` unless you pass `{ allowExternal: true }`.
319
- ```ts
320
- return redirect("/dashboard"); // 302
321
- return redirect("/login", 303); // custom status
322
- return redirect("/x", 302, { "Set-Cookie": cookie }); // with headers
323
- return redirect("https://other.com", 302, undefined, { allowExternal: true });
324
- ```
325
-
326
- ### `error(message, status?)`
327
- Convenience JSON error: `{ "error": message }` with the given status (default 500).
328
- ```ts
329
- return error("Bad Request", 400);
330
- ```
331
-
332
- ### `HttpError` & `BractJSError`
333
- Throw a typed HTTP error from a loader/action. The framework converts it to a response with that status (and a default status text if you omit the message).
334
- ```ts
335
- throw new HttpError(403); // → 403 Forbidden
336
- throw new HttpError(404, "No such post"); // → 404 with custom message
337
- ```
338
- `isRedirect(value)` / `isHttpError(value)` / `isBractJSError(value)` are type guards if you handle errors manually.
339
-
340
- ---
341
-
342
- ## 7. Per-route context: `defineContext`
343
-
344
- A route can compute request-scoped data once and share it with all its loaders/actions via the `context` argument. Middleware can also populate `context` (§14) — `defineContext` is the per-route version.
345
-
346
- ```ts
347
- // app/routes/dashboard.tsx
348
- import { defineContext } from "@bractjs/bractjs";
349
- import { getUser } from "../auth.server.ts";
350
-
351
- export const context = defineContext(async ({ request, params }) => ({
352
- user: await getUser(request),
353
- }));
354
-
355
- export function beforeLoad({ context }) {
356
- if (!context.user) return redirect("/login");
357
- }
358
-
359
- export async function loader({ context }) {
360
- return { name: context.user.name };
361
- }
362
- ```
363
-
364
- The factory runs before `beforeLoad` and its result is merged into `context` for `beforeLoad`, `loader`, and `action` on that route.
365
-
366
- ---
367
-
368
- ## 8. Streaming data
369
-
370
- Stream slow data without blocking the initial HTML.
371
-
372
- ```ts
373
- import { defer, Deferred, isDeferred } from "@bractjs/bractjs";
374
- import { Await } from "@bractjs/bractjs";
375
- import { Suspense } from "react";
376
- ```
377
-
378
- ### `defer(data)`
379
- Wraps each `Promise` field in a `Deferred`; non-promise fields pass through. Awaited fields are in the initial HTML; promises stream after.
380
-
381
- ```tsx
382
- export async function loader({ params }: LoaderArgs) {
383
- return defer({
384
- post: await db.post.findById(params.id), // awaited → initial HTML
385
- comments: db.comments.forPost(params.id), // Promise → streamed
386
- });
387
- }
388
-
389
- export default function BlogPost() {
390
- // useLoaderData<typeof loader>() infers the shape — `comments` stays a
391
- // Deferred<Comment[]>, which <Await> accepts directly.
392
- const { post, comments } = useLoaderData<typeof loader>();
393
- return (
394
- <article>
395
- <h1>{post.title}</h1>
396
- <Await resolve={comments} fallback={<p>Loading comments…</p>}>
397
- {(c) => <CommentList comments={c} />}
398
- </Await>
399
- </article>
400
- );
401
- }
402
- ```
403
-
404
- ### `<Await resolve={promise | Deferred} fallback={…}>{(data) => …}</Await>`
405
- Unwraps a promise (or a `Deferred` field from a `defer()` loader) with React 19's `use()` inside its own `<Suspense>`. `isDeferred(value)` and the `Deferred` class are exported if you need to detect/construct deferred values manually.
406
-
407
- ---
408
-
409
- ## 9. Client hooks
410
-
411
- All hooks are SSR-safe (they return sensible values during SSR) and imported from `@bractjs/bractjs`.
412
-
413
- ### `useLoaderData<T>()` → `T`
414
- The current route's loader return value. **Pass the loader function type** to infer it (`Response` branch excluded, `Deferred` fields preserved) — no hand-written type to keep in sync. An explicit object type still works.
415
- ```ts
416
- const { post } = useLoaderData<typeof loader>(); // inferred from loader()
417
- const { post } = useLoaderData<LoaderData>(); // or an explicit type
418
- ```
419
-
420
- ### `useActionData<T>()` → `T | null`
421
- The most recent action return value (null until an action runs). Like `useLoaderData`, accepts the action function type.
422
- ```ts
423
- const result = useActionData<typeof action>();
424
- ```
425
-
426
- ### `useParams<T>()` → `T`
427
- URL dynamic params. Pass the **route pattern** as a generic to type the result against your codegen'd routes (see §18); an object shape also works.
428
- ```ts
429
- const { id } = useParams<"/blog/:id">(); // { id: string } — typed from routes
430
- const { id } = useParams<{ id: string }>(); // or a hand-written shape
431
- ```
432
- > The pattern is supplied by the caller because the framework can't infer the active route at the type level (React Router's `useParams` works the same way).
433
-
434
- ### `useLocation()` → `{ pathname, search, hash, state, key }`
435
- The current location — reactive on the client, request-derived during SSR (`hash` is always `""` there). `key` is the history entry's identity (what scroll restoration uses); `state` is whatever you passed via `navigate(to, { state })`.
436
- ```ts
437
- const location = useLocation();
438
- const isActive = location.pathname.startsWith("/blog");
439
- ```
440
-
441
- ### `useNavigation()` → `{ state }`
442
- `"idle" | "loading" | "submitting"`. Form/`submit()` mutations walk `"submitting"` → `"loading"` (revalidation) → `"idle"`.
443
- ```ts
444
- const { state } = useNavigation();
445
- if (state === "loading") return <Spinner />;
446
- ```
447
-
448
- ### `useNavigate()` → `(to, { params?, search?, replace?, state? }) => Promise<void>`
449
- Imperative soft navigation — the counterpart to `<Link>`. `to` autocompletes your routes (after codegen, §18); `params` and `search` are typed per route; any string is still accepted.
450
- ```ts
451
- const navigate = useNavigate();
452
- await navigate("/blog/:id", { params: { id: "42" } }); // typed
453
- await navigate("/posts", { search: { page: 2 } }); // typed search → /posts?page=2
454
- await navigate("/login", { replace: true }); // replaceState, no history entry
455
- await navigate("/wizard/2", { state: { from: "step1" } }); // read via useLocation().state
456
- ```
457
-
458
- ### `useRevalidator()` → `{ revalidate, state }`
459
- Manually re-run the current route's loaders — for "Refresh" buttons, polling, or after out-of-band changes (e.g. a WebSocket event). Respects the route's `shouldRevalidate`. `state` is `"idle" | "loading"` and tracks only revalidation (navigations are `useNavigation()`).
460
- ```ts
461
- const { revalidate, state } = useRevalidator();
462
- <button onClick={() => void revalidate()} disabled={state === "loading"}>Refresh</button>
463
- ```
464
-
465
- ### `useSearch()` / `useSetSearch()` — typed, validated search params
466
- `useSearch` returns the route's **validated** search object (the `searchSchema` output — numbers are numbers, defaults applied). Validation runs once on the server; the client never re-runs the schema. `useSetSearch` merges a patch, writes the URL, and soft-navigates so loaders re-run. Set a key to `undefined` to delete it.
467
- ```ts
468
- const search = useSearch<"/posts">(); // { page: number; q?: string }
469
- const setSearch = useSetSearch<"/posts">();
470
- setSearch({ page: search.page + 1 }); // patch → /posts?page=2&q=…
471
- setSearch((prev) => ({ q: undefined }), { replace: true }); // delete + replaceState
472
- ```
473
-
474
- ### `useSearchParams<T>()` → `{ searchParams, getParam, setSearchParams }`
475
- The low-level escape hatch: raw string `URLSearchParams` read/write; writing triggers a soft-nav loader re-run. Prefer `useSearch`/`useSetSearch` (above) when the route has a `searchSchema`.
476
- ```ts
477
- const { searchParams, getParam, setSearchParams } = useSearchParams<"/blog/:id">();
478
- const q = getParam("q"); // string | null
479
- setSearchParams({ q: "bun" }); // replace all params
480
- setSearchParams((prev) => { prev.set("page", "2"); return prev; }); // update
481
- ```
482
-
483
- ### `useFetcher({ key? })` → `{ data, state, formData, formMethod, load, submit, Form, key }`
484
- Background fetch/mutation without navigating. After a `submit`, the active route's loaders revalidate automatically (gated by `shouldRevalidate`). `formData`/`formMethod` are set from the moment `submit` is called — render them for **optimistic UI**. A `key` gives the fetcher a stable identity shared across components and surviving remounts; unkeyed fetchers are component-bound.
485
- ```ts
486
- const fetcher = useFetcher({ key: `delete-${id}` });
487
- await fetcher.load("/products?q=bun"); // GET loader data
488
- await fetcher.submit("/cart", { method: "post", body: { id: "1" } });
489
- const optimisticTitle = fetcher.formData?.get("title"); // while submitting
490
- <fetcher.Form method="post" action="/cart">…</fetcher.Form> {/* scoped form, no navigation */}
491
- ```
492
-
493
- ### `useFetchers()` → `FetcherEntry[]`
494
- Every active fetcher — the cross-component view for optimistic UI (e.g. dim each table row whose keyed delete fetcher is in flight elsewhere in the tree).
495
- ```ts
496
- const deleting = new Set(
497
- useFetchers()
498
- .filter((f) => f.state === "submitting" && f.key.startsWith("delete-"))
499
- .map((f) => f.key.slice("delete-".length)),
500
- );
501
- ```
502
-
503
- ### `useFetcher<T>({ stream: true })` → `{ connect }`
504
- Consume an async-generator server action as an SSE stream.
505
- ```ts
506
- const { connect } = useFetcher<string>({ stream: true });
507
- for await (const chunk of connect(actionId)) { /* … */ }
508
- ```
509
-
510
- ### `useBlocker(shouldBlock)`
511
- Prompt before leaving when there are unsaved changes (intercepts back/forward and `<Link>` navigations).
512
- ```ts
513
- useBlocker(() => formIsDirty);
514
- ```
515
-
516
- ### `useLocale(defaultLocale?)` → `string` and `useLocalizedLink(defaultLocale?)` → `(path) => string`
517
- For i18n prefix routing (§19).
518
- ```ts
519
- const locale = useLocale("en"); // reads params.locale
520
- const localized = useLocalizedLink("en");
521
- <Link to={localized("/about")} /> // → /en/about
522
- ```
523
-
524
- ---
525
-
526
- ## 10. Client components
527
-
528
- ### `<Outlet />`
529
- Renders the matched child route inside a layout (or the route tree inside `root.tsx`).
530
- ```tsx
531
- export default function BlogLayout() {
532
- return <div><nav>Blog</nav><Outlet /></div>;
533
- }
534
- ```
535
-
536
- ### `<Link to params? search? prefetch? replace? viewTransition?>`
537
- Soft-navigates without a full reload. After codegen (§18), `to` autocompletes your routes; for a dynamic route pass typed `params`, and `search` is typed by the target's `searchSchema`. Building the URL yourself still works, so existing links need no changes.
538
- ```tsx
539
- <Link to="/blog/:id" params={{ id: "42" }}>Read</Link> {/* typed route + params */}
540
- <Link to={`/blog/${id}`}>Read</Link> {/* built string — also fine */}
541
- <Link to="/posts" search={{ page: 2 }}>Page 2</Link> {/* typed search params */}
542
- <Link to="/about" prefetch="intent">About</Link> {/* preload on hover/focus intent */}
543
- <Link to="/gallery" viewTransition>Gallery</Link> {/* use View Transitions API */}
544
- ```
545
- Modifier-clicks (ctrl/cmd/shift/alt) fall back to native browser navigation.
546
-
547
- **Prefetch modes** — prefetching warms the route chunk (`modulepreload`) *and* the loader cache, so the click commits instantly (prefetched data stays fresh ≥ 30s; concurrent data prefetches are capped at 6 so long lists can't stampede the server):
548
-
549
- | mode | when |
550
- |---|---|
551
- | `"none"` (default) | never |
552
- | `"intent"` | hover **or focus**, after a 100 ms delay (canceled on fly-by) — best default |
553
- | `"hover"` | immediately on mouseenter (legacy alias) |
554
- | `"viewport"` | when the link scrolls into view (one shared IntersectionObserver) — for lists |
555
- | `"render"` | as soon as the link mounts |
556
-
557
- ### `<ScrollRestoration getKey? storageKey?>`
558
- Restores the window scroll position on back/forward (and reload), scrolls to top — or to the `#hash` element — on new navigations. Render it **once** in `app/root.tsx`, next to `<Scripts />`. Positions persist in `sessionStorage`. Pass `getKey={(location) => location.pathname}` to share one position across every visit to the same path.
559
- ```tsx
560
- <body>
561
- <Outlet />
562
- <ScrollRestoration />
563
- <Scripts />
564
- </body>
565
- ```
566
-
567
- ### `<Form method action?>`
568
- Fetch-based submission that re-runs the current route's loader after the action.
569
- ```tsx
570
- <Form method="post">
571
- <input name="title" />
572
- <button type="submit">Create</button>
573
- </Form>
574
- <Form method="post" action="/blog/new">…</Form>
575
- ```
576
- Submits as `multipart/form-data` with the `X-BractJS-Action` header (CSRF gate). If the action returns a redirect, the form follows it.
577
-
578
- ### `<Scripts />` and `<LiveReload />`
579
- Markers used inside `root.tsx` (§3). `<Scripts />` is where the client bundle + bootstrap data go; `<LiveReload />` is the dev-only HMR client.
580
-
581
- ### `<Image />`
582
- Responsive, format-converted images via the built-in `/_image` endpoint — see §20.
583
-
584
- ---
585
-
586
- ## 11. Server Actions & Client Components
587
-
588
- ### `"use server"` — Server Actions
589
-
590
- Mark a file's exports as server actions by making `"use server"` the first line. On the **client**, imports become `fetch("/_action?id=<hash>")` proxies; on the **server**, the real function runs. Action IDs are `SHA-256(appDir-relative-path + "#" + name)`.
591
-
592
- ```ts
593
- // app/actions.ts
594
- "use server";
595
-
596
- export async function createPost(formData: FormData) {
597
- const title = formData.get("title") as string;
598
- await db.insert(posts).values({ title });
599
- return { ok: true };
600
- }
601
-
602
- export async function deletePost(id: string) {
603
- await db.delete(posts).where(eq(posts.id, id));
604
- }
605
- ```
606
-
607
- ```tsx
608
- // app/routes/new.tsx — import as normal; the client bundle gets a fetch proxy
609
- import { createPost } from "../actions.ts";
610
-
611
- export default function NewPost() {
612
- return (
613
- <form action={createPost}>
614
- <input name="title" />
615
- <button type="submit">Create</button>
616
- </form>
617
- );
618
- }
619
- ```
620
-
621
- - Accepts a single `FormData` (sent as `multipart/form-data`) **or** a JSON-serializable argument array.
622
- - Unknown action IDs return 404 — only functions registered at startup are callable.
623
- - Bodies are size-capped (1 MiB JSON) and prototype-pollution scanned.
624
-
625
- **Streaming server actions** (async generators) are consumed with `useFetcher({ stream: true })` (§9) over `/_stream`. The endpoint requires the `X-BractJS-Action` header (set automatically by the client).
626
-
627
- ### `"use client"` — Client-Only Components
628
-
629
- Mark a component browser-only. During server builds the module is stubbed to `null` to prevent `window`/`document`/`localStorage` crashes during SSR.
630
-
631
- ```tsx
632
- // app/components/Counter.tsx
633
- "use client";
634
- import { useState } from "react";
635
-
636
- export function Counter() {
637
- const [n, setN] = useState(0);
638
- return <button onClick={() => setN(n + 1)}>Count: {n}</button>;
639
- }
640
- ```
641
-
642
- ---
643
-
644
- ## 12. Typed API routes
645
-
646
- Define type-safe JSON endpoints under `/api/*` with `route`, and call them with a fully-typed `createClient`.
647
-
648
- ### Define routes with `route(method, path, handler)`
649
-
650
- ```ts
651
- // app/api/users.ts
652
- import { route } from "@bractjs/bractjs";
653
- import { db } from "../db.server.ts";
654
-
655
- export const listUsers = route("GET", "/api/users", async () => {
656
- return db.users.findAll();
657
- });
658
-
659
- export const createUser = route("POST", "/api/users", async (input: { name: string }) => {
660
- return db.users.create(input);
661
- });
662
- ```
663
-
664
- - `GET`/`DELETE`: no body parsed. `POST`/`PUT`/`PATCH`: JSON or form body parsed into `input`.
665
- - Bodies are capped at 1 MiB. Errors return a generic 500 in production (full message in dev).
666
- - Handlers also receive the raw `Request` as the 2nd arg.
667
- - `:param` segments match any non-empty value; **read and validate params from `request.url` yourself** (they aren't injected into `input`).
668
-
669
- ### Call them with `createClient<AppApiRoutes>()`
670
-
671
- ```ts
672
- import { createClient } from "@bractjs/bractjs";
673
- import type { AppApiRoutes } from "@bractjs/bractjs"; // union of your route defs
674
-
675
- const client = createClient<AppApiRoutes>(); // optional baseUrl arg
676
- const users = await client["/api/users"].GET(); // typed output
677
- await client["/api/users"].POST({ name: "Alice" }); // typed input
678
- ```
679
-
680
- The proxy builds `METHOD path` from the property chain. Non-2xx responses throw an `Error` with `.status` and `.response` attached.
681
-
682
- ---
683
-
684
- ## 13. Input validation: `validate`
685
-
686
- Validate `FormData` or a plain object against any **Zod- or Valibot-compatible** schema (anything with `.safeParse()` or `.parse()`).
687
-
688
- ```ts
689
- import { validate } from "@bractjs/bractjs";
690
- import { z } from "zod";
691
-
692
- const Schema = z.object({ title: z.string().min(1), tags: z.array(z.string()) });
693
-
694
- export async function action({ formData }: ActionArgs) {
695
- // Throws a 400 Response with { errors: { field: [msgs] } } on failure.
696
- const data = await validate(Schema, formData);
697
- await db.post.create(data); // data is fully typed + coerced
698
- }
699
- ```
700
-
701
- - Repeated `FormData` keys become arrays automatically.
702
- - On failure it throws a `Response.json({ errors }, { status: 400 })`. The exported `ValidationError` type and `FieldErrors` shape describe the structure.
703
-
704
- ### `safeValidate` — validate without try/catch (recommended for inline form errors)
705
-
706
- Returns a result instead of throwing — the clean idiom when you want to render field errors rather than a 400 page. `firstError` is the first field message.
707
- ```ts
708
- import { safeValidate } from "@bractjs/bractjs";
709
-
710
- export const action = defineActions({
711
- create: async ({ formData }) => {
712
- const r = await safeValidate(Schema, formData);
713
- if (!r.ok) return { error: r.firstError, fieldErrors: r.fieldErrors };
714
- await db.post.create(r.data); // r.data is typed + coerced
715
- return redirect("/blog");
716
- },
717
- });
718
- ```
719
- If you prefer to keep calling `validate()` and catching: `isValidationResponse(err)` narrows the thrown 400, and `readValidationError(res)` parses it into `{ fieldErrors, firstError }`.
720
-
721
- ### FormData helpers
722
-
723
- `formText(formData, key)` returns a string (`""` for missing or File values) — no more `String(formData.get(k) ?? "")`. `formValues(formData, keys?)` collects string fields into an object (all, or a named subset).
724
-
725
- ---
726
-
727
- ## 14. Middleware
728
-
729
- Middleware runs **before routing** on the module-level `pipeline` singleton. Each middleware gets `(ctx, next)` and returns a `Response`. `ctx.context` is threaded into every loader/action.
730
-
731
- ```ts
732
- import { pipeline, requestLogger, cors, authGuard, csp } from "@bractjs/bractjs";
733
- import type { MiddlewareFn } from "@bractjs/bractjs";
734
-
735
- pipeline
736
- .use(requestLogger())
737
- .use(cors({ origin: "https://myapp.com" }))
738
- .use(csp())
739
- .use(authGuard({ session }));
740
- ```
741
-
742
- ### Built-in middleware
743
-
744
- | Middleware | What it does |
745
- |---|---|
746
- | `requestLogger()` | Logs `[METHOD] /path → status in Xms`. Never logs the query string or headers (token-leak safe). |
747
- | `cors(options)` | Sets CORS headers, handles `OPTIONS` preflight (204), always sets `Vary: Origin`, refuses `credentials:true` + `origin:"*"`. |
748
- | `authGuard(options)` | Reads the session, sets `ctx.context.user`; with `required:true` returns 401 when unauthenticated. |
749
- | `csp(options?)` | Opt-in nonce-based Content-Security-Policy (see below). |
750
-
751
- **`cors(options)`** — `{ origin: string | string[]; methods?: string[]; credentials?: boolean }`:
752
- ```ts
753
- pipeline.use(cors({ origin: ["https://a.com", "https://b.com"], credentials: true }));
754
- ```
755
-
756
- **`authGuard(options)`** — `{ session: SessionStorageLike; required?: boolean }`:
757
- ```ts
758
- pipeline.use(authGuard({ session, required: true })); // 401 if no session.user
759
- ```
760
-
761
- **`csp(options?)`** — generates a per-request nonce, applies it to the scripts BractJS injects (via `renderToReadableStream`'s `nonce`), and sets the CSP header:
762
- ```ts
763
- pipeline.use(csp({
764
- directives: { "img-src": "'self' data: https://cdn.example", "frame-ancestors": "'none'" },
765
- reportOnly: false, // true → Content-Security-Policy-Report-Only
766
- strict: false, // true → drop 'unsafe-inline' from style-src (see below)
767
- }));
768
- ```
769
- Read the nonce inside a component/middleware with `getCspNonce(context)` (key: `CSP_NONCE_KEY`) to nonce your own inline scripts.
770
-
771
- `script-src` is always nonce-based (`'nonce-…' 'strict-dynamic'`), so injected `<script>` cannot execute. The default `style-src` allows `'unsafe-inline'` for ergonomics (React inline styles, CSS-in-JS); this leaves inline-style injection possible. Pass `strict: true` (or override `style-src` with a nonce/hash) if your app serves all styles from same-origin stylesheets.
772
-
773
- ### Custom middleware
774
-
775
- ```ts
776
- import type { MiddlewareFn } from "@bractjs/bractjs";
777
-
778
- const trace: MiddlewareFn = async (ctx, next) => {
779
- ctx.context.requestId = crypto.randomUUID();
780
- const res = await next();
781
- res.headers.set("X-Request-Id", ctx.context.requestId as string);
782
- return res;
783
- };
784
- pipeline.use(trace);
785
- ```
786
-
787
- You can also construct an isolated `new MiddlewarePipeline()` and `.run(ctx, handler)` it yourself (used internally and in tests).
788
-
789
- ---
790
-
791
- ## 15. Sessions
792
-
793
- Signed, tamper-proof cookie sessions (HMAC-SHA256, constant-time verify, secret rotation).
794
-
795
- ```ts
796
- import { createCookieSession } from "@bractjs/bractjs";
797
-
798
- const session = createCookieSession({
799
- name: "__session",
800
- secrets: [Bun.env.SESSION_SECRET!], // first signs; all verify (rotate by prepending)
801
- maxAge: 60 * 60 * 24 * 7, // seconds; 1 week
802
- secure: true, // false only for local HTTP dev
803
- sameSite: "Lax", // "Strict" | "Lax" | "None"
804
- });
805
- ```
806
-
807
- Read in a loader, write in an action:
808
-
809
- ```ts
810
- export async function loader({ request }: LoaderArgs) {
811
- const s = await session.getSession(request.headers.get("Cookie"));
812
- return { user: s.get("user") };
813
- }
814
-
815
- export async function action({ request }: ActionArgs) {
816
- const s = await session.getSession(request.headers.get("Cookie"));
817
- s.set("user", { id: 1, name: "Alice" }); // also: s.get, s.has, s.delete
818
- return redirect("/dashboard", {
819
- headers: { "Set-Cookie": await session.commitSession(s) }, // opt: { maxAge }
820
- });
821
- }
822
- ```
823
-
824
- - Each secret must be ≥16 chars; `secrets` must be non-empty (throws otherwise).
825
- - Tampered cookies are silently rejected → empty session.
826
- - Generate a secret: `openssl rand -base64 32`.
827
-
828
- ---
829
-
830
- ## 16. Lifecycle hooks: `defineLifecycle`
831
-
832
- Run code on server start, shutdown, and unexpected errors. Shutdown fires on **any** exit signal (`SIGTERM`, `SIGINT`, `SIGUSR2`, `beforeExit`, uncaught exceptions).
833
-
834
- ```ts
835
- // app/lifecycle.ts
836
- import { defineLifecycle } from "@bractjs/bractjs";
837
- import { db } from "./db.server.ts";
838
-
839
- export default defineLifecycle({
840
- async onStart() { await db.connect(); },
841
- async onShutdown(){ await db.disconnect(); },
842
- onError(err, request) {
843
- Sentry.captureException(err, { extra: { url: request?.url } });
844
- },
845
- });
846
- ```
847
-
848
- | Hook | When |
849
- |------|------|
850
- | `onStart` | Once, after the server starts listening. |
851
- | `onShutdown` | Before exit — any signal, programmatic `stop()`, or uncaught exception. |
852
- | `onError` | Every unexpected error (loader/action throws, uncaught exceptions). Redirects and `HttpError`s are intentional control flow and are **not** reported. `request` is `undefined` for process-level exceptions. |
853
-
854
- - **Dev** picks up `app/lifecycle.ts` automatically.
855
- - **Production**: spread into `createServer()`:
856
- ```ts
857
- import { createServer } from "@bractjs/bractjs";
858
- import lifecycle from "./app/lifecycle.ts";
859
- createServer({ port: 3000, ...lifecycle });
860
- ```
861
-
862
- `createServer()` returns `{ stop }`. `stop()` runs `onShutdown` and closes the listener but does **not** call `process.exit()` (good for tests/supervisors). Signals do exit.
863
-
864
- ---
865
-
866
- ## 17. Environment variables
867
-
868
- | Convention | Behavior |
869
- |---|---|
870
- | `*.server.ts` / `*.server.tsx` | **Stubbed out of the client bundle.** Import it freely from a route's `loader`/`action`; every export is replaced by an inert stub in the browser build, so the real source (DB drivers, secrets, `bun:sqlite`) never ships. The stub throws if you accidentally call it on the client. |
871
- | Keys listed in `clientEnv` | Replaced with string literals in the client bundle. |
872
- | Any other `process.env.*` | Becomes the literal `"undefined"` in the client bundle. |
873
-
874
- ```ts
875
- // db.server.ts — never reaches the browser
876
- import { Database } from "bun:sqlite";
877
- export const db = new Database(Bun.env.DATABASE_URL!);
878
- ```
879
-
880
- ```ts
881
- // app/routes/posts.tsx — import the server module inside the loader
882
- import { db } from "../db.server.ts"; // stubbed in the client bundle
883
-
884
- export async function loader() {
885
- return { posts: db.query("SELECT * FROM posts").all() };
886
- }
887
- ```
888
-
889
- > BractJS ships the whole route module — `loader` and `action` included — to the client, so a server import is reachable from the client graph. The `serverModuleStubPlugin` (applied automatically by `bractjs dev`/`build`) replaces every `*.server.ts` export with a throwing stub: the import resolves, the loader/action are dead code on the client, and **zero** server source is emitted. The stricter, hard-failing `serverOnlyPlugin` is still exported if you'd rather a server import be a build error.
890
-
891
- ```ts
892
- // bractjs.config.ts
893
- export default { clientEnv: ["PUBLIC_API_URL"] };
894
- ```
895
-
896
- ```ts
897
- // in a client component — only allow-listed keys survive
898
- fetch(`${process.env.PUBLIC_API_URL}/items`);
899
- ```
900
-
901
- On the server, read env via `Bun.env.*` directly.
902
-
903
- ---
904
-
905
- ## 18. Typed routes
906
-
907
- Generate type-safe routing from your route files — one command wires `<Link>`, `useNavigate`, `useParams`, and `useSearchParams` to your actual routes.
908
-
909
- ```sh
910
- bractjs codegen # ./app → ./app/route-types.gen.ts
911
- bractjs codegen ./app ./app/types.ts # explicit paths
912
- ```
913
-
914
- **You rarely run this by hand.** `bractjs new` generates it on scaffold, `bractjs dev` regenerates it on boot and whenever you add/remove/rename a route file, and `bractjs build` runs it too. The output is deterministic (route-sorted) and carries a `// bractjs:routes <hash>` fingerprint, so re-runs that change nothing don't rewrite the file (no editor reload loops); on boot the dev server prints precisely what drifted. Make sure the generated file is part of your TypeScript program (it is, if your `tsconfig.json` `include`s `app/`). It augments BractJS's `Register` interface, after which the runtime components and hooks become type-safe — **no per-route imports needed**:
915
-
916
- ```tsx
917
- <Link to="/blog/:id" params={{ id }} /> // ✅ "/blog/:id" autocompletes; params typed
918
- <Link to="/blgo/:id" params={{ id }} /> // ❌ typo'd route — compile error
919
- <Link to="/blog/:id" params={{ x: id }} /> // ❌ wrong param key — compile error
920
-
921
- const navigate = useNavigate();
922
- navigate("/blog/:id", { params: { id } }); // ✅ same typing as <Link>
923
-
924
- const { id } = useParams<"/blog/:id">(); // id: string
925
- ```
926
-
927
- Building the URL yourself (`<Link to={`/blog/${id}`}>`) still type-checks, so adopting codegen never breaks existing links.
928
-
929
- The generated file also exports types/helpers for typed loaders and explicit URL building:
930
-
931
- ```ts
932
- import type { TypedLoaderArgs } from "../route-types.gen.ts";
933
- import { routes } from "../route-types.gen.ts";
934
-
935
- export async function loader({ params }: TypedLoaderArgs<"/blog/:id">) {
936
- return db.post.findById(params.id); // params.id: string
937
- }
938
- routes["/blog/:id"]({ id: "123" }); // → "/blog/123" (typo'd routes won't compile)
939
- ```
940
-
941
- **Type a route's search params or context** by augmenting the package interfaces — `SearchParams<T>` / `Context<T>` and `useSearchParams<T>()` pick it up:
942
-
943
- ```ts
944
- declare module "@bractjs/bractjs" {
945
- interface RouteSearchParamsMap { "/blog": { page: string; sort: string } }
946
- interface RouteContextMap { "/admin": { user: { id: string; role: "admin" } } }
947
- }
948
- ```
949
-
950
- You can also call `writeRouteTypes(appDir, outPath?)` / `generateRouteTypes(appDir)` programmatically.
951
-
952
- > **Heads up:** earlier versions documented `useParams<RouteParams<"/blog/:id">>()` and untyped `<Link to={string}>`. The route-literal form (`useParams<"/blog/:id">()`) and typed `<Link>`/`useNavigate` are the current API; the old forms still compile.
953
-
954
- ---
955
-
956
- ## 19. Internationalization utilities
957
-
958
- BractJS exports **utilities** for locale-prefixed routing. These are helpers you wire up yourself (there is no fully-automatic locale router yet) plus the `useLocale` / `useLocalizedLink` client hooks (§9).
959
-
960
- ```ts
961
- import { wrapRoutesWithLocale, stripLocale, localizedDataPath } from "@bractjs/bractjs";
962
- import type { I18nConfig } from "@bractjs/bractjs";
963
-
964
- const i18n: I18nConfig = { locales: ["en", "fr"], defaultLocale: "en" };
965
-
966
- // Add /:locale-prefixed variants alongside the originals.
967
- const localized = wrapRoutesWithLocale(routeFiles, i18n);
968
-
969
- // Split a locale off a pathname.
970
- const { locale, strippedPathname } = stripLocale("/fr/about", i18n.locales);
971
- // → { locale: "fr", strippedPathname: "/about" }
972
-
973
- // Build a locale-aware data path.
974
- localizedDataPath("/about", "fr"); // → "/fr/about"
975
- ```
976
-
977
- On the client, read the active locale and build localized links:
978
-
979
- ```tsx
980
- const locale = useLocale("en");
981
- const to = useLocalizedLink("en");
982
- <Link to={to("/about")} />; // → /en/about
983
- ```
984
-
985
- ---
986
-
987
- ## 20. Image optimization
988
-
989
- `<Image>` serves responsive, format-converted images through the built-in `/_image` endpoint. Requires [ImageMagick](https://imagemagick.org) (`magick` or `convert`) — without it, originals are served as-is.
990
-
991
- ```tsx
992
- import { Image } from "@bractjs/bractjs";
993
-
994
- <Image src="/public/hero.jpg" alt="Hero" width={1200} height={600} />
995
-
996
- {/* above-the-fold: eager + fetchpriority=high */}
997
- <Image src="/public/hero.jpg" alt="Hero" width={1200} priority />
998
-
999
- <Image
1000
- src="/public/photo.jpg" alt="Photo" width={800}
1001
- format="avif" quality={70} fit="contain"
1002
- sizes="(max-width: 640px) 100vw, 50vw"
1003
- />
1004
- ```
1005
-
1006
- | Prop | Type | Default | Notes |
1007
- |------|------|---------|-------|
1008
- | `src` | `string` | — | Path under `/public/` (required) |
1009
- | `alt` | `string` | — | Required |
1010
- | `width` / `height` | `number` | — | Intrinsic size |
1011
- | `quality` | `number` | `80` | 1–100 |
1012
- | `format` | `"webp" \| "avif" \| "jpeg" \| "png"` | `"webp"` | `ImageFormat` |
1013
- | `fit` | `"cover" \| "contain" \| "fill"` | `"cover"` | `ImageFit` |
1014
- | `priority` | `boolean` | `false` | Disable lazy load, set `fetchpriority=high` |
1015
- | `sizes` | `string` | `"100vw"` | HTML `sizes` |
1016
-
1017
- Generates a `srcset` across breakpoints (320→1920px). Optimized images are cached in memory (LRU, 200 slots) and on disk (`.bract-image-cache/`, survives restarts), both served `Cache-Control: immutable`. The endpoint validates widths against an allowlist, caps total pixel area, limits concurrency, and kills runaway transforms (DoS hardening).
1018
-
1019
- `ImageProps`, `ImageFormat`, and `ImageFit` are exported types.
1020
-
1021
- ---
1022
-
1023
- ## 21. Build & run
1024
-
1025
- ### CLI
1026
-
1027
- | Command | Description |
1028
- |---------|-------------|
1029
- | `bractjs new <name>` | Scaffold a new app into `<name>/`. |
1030
- | `bractjs dev` | Dev server with HMR (port 3000, HMR ws 3001). |
1031
- | `bractjs build` | Dual server + client build with content-hashed output. |
1032
- | `bractjs start` | Serve the production build. |
1033
- | `bractjs codegen [app] [out]` | Generate `route-types.gen.ts`. |
1034
- | `bractjs codegen:registry [app]` | Generate `app/_generated/{routes,actions}.ts`. |
1035
- | `bractjs codegen:manifest [app] [build]` | Snapshot manifest → `app/_generated/manifest.ts`. |
1036
- | `bractjs compile [outfile] [entry]` | Full single-binary pipeline. |
1037
-
1038
- The CLI is a thin wrapper — every command delegates to a public function, so you can script the same thing.
1039
-
1040
- ### Programmatic API
1041
-
1042
- **`createDevServer(options?)`** — dev server with HMR.
1043
- ```ts
1044
- import { createDevServer } from "@bractjs/bractjs";
1045
-
1046
- const dev = await createDevServer({
1047
- port: 3000, // default: config.port ?? 3000
1048
- hmrPort: 3001, // HMR websocket
1049
- config: { appDir: "./app", clientEnv: ["PUBLIC_API_URL"] },
1050
- skipUserConfig: false, // true → don't read bractjs.config.ts
1051
- });
1052
- dev.stop();
1053
- ```
1054
-
1055
- **`runBuild(config?)`** — production build (accepts only build-relevant fields).
1056
- ```ts
1057
- import { runBuild } from "@bractjs/bractjs";
1058
-
1059
- await runBuild({
1060
- appDir: "./app",
1061
- buildDir: "./build",
1062
- minify: true,
1063
- sourcemap: "external", // "none" | "linked" | "inline" | "external"
1064
- clientEnv: ["PUBLIC_API_URL"],
1065
- plugins: [], // extra Bun plugins
1066
- });
1067
- ```
1068
-
1069
- **`loadUserConfig()`** — read `bractjs.config.ts` (or `.js`) from cwd, validated.
1070
- ```ts
1071
- import { loadUserConfig } from "@bractjs/bractjs";
1072
- const cfg = await loadUserConfig(); // {} if no file; throws on a malformed shape
1073
- ```
1074
-
1075
- **`createServer(config?)`** — production HTTP server. Returns `{ stop }`.
1076
- ```ts
1077
- import { createServer } from "@bractjs/bractjs";
1078
- import lifecycle from "./app/lifecycle.ts";
1079
- const srv = createServer({ port: 3000, buildDir: "./build", ...lifecycle });
1080
- ```
1081
-
1082
- **`buildFetchHandler(config)`** — the adapter-agnostic `(Request) => Promise<Response>` core, if you want to mount BractJS inside another server.
1083
- ```ts
1084
- import { buildFetchHandler } from "@bractjs/bractjs";
1085
- const handler = buildFetchHandler({ appDir: "./app", manifest });
1086
- Bun.serve({ port: 3000, fetch: handler });
1087
- ```
1088
-
1089
- `renderRoute(options)` (low-level SSR render) and the `RenderOptions`/`ServerManifest`/`BractJSConfig` types are also exported for advanced embedding.
1090
-
1091
- ### Rendering modes
1092
-
1093
- Three levels of SSR control, all opt-in:
1094
-
1095
- **Per-route selective SSR** — `export const ssr = false | "data-only"` plus a `Fallback` component on any route (§5 item 8). The document SSRs the Fallback; the client swaps in the real component after hydration. `beforeLoad` always runs server-side.
1096
-
1097
- **App-wide SPA mode** — `ssr: false` in `bractjs.config.ts`:
1098
-
1099
- ```ts
1100
- // bractjs.config.ts
1101
- export default {
1102
- ssr: false, // every document GET serves one static shell
1103
- };
1104
- ```
1105
-
1106
- SPA mode means **"no document SSR", not "no server"**: the Bun server keeps serving `/_data` (loaders), `/_action`/mutations (CSRF gate intact), `/_image`, API routes, and static assets. `bractjs build` emits the shell at `build/client/__spa.html`; in dev it renders on the fly so `root.tsx` edits show up. Constraints: the root component renders without loader data and with a `/` location, so keep location/loader-dependent markup out of `root.tsx`; route-level `meta()` only applies after hydration (no SEO for route content).
1107
-
1108
- **Build-time prerendering (SSG)** — `prerender` in `bractjs.config.ts`:
1109
-
1110
- ```ts
1111
- // bractjs.config.ts
1112
- export default {
1113
- prerender: ["/", "/about", "/blog/intro"],
1114
- // or resolve dynamically: prerender: async () => (await db.posts()).map(p => `/blog/${p.slug}`),
1115
- };
1116
- ```
1117
-
1118
- `bractjs build` runs the real loaders in-process (anything they need — DB, env — must be available at build time), writing each path's HTML **and** its `/_data` payload (used by client navigations *into* a prerendered page) under `build/client/_prerender/`. In production, clean URLs are served from these files before dynamic SSR; **a query string opts the request back into SSR** (the file was rendered without one). Paths must be concrete — expand `"/blog/:slug"` yourself; the build fails on patterns. `runPrerender(options)` is exported for custom pipelines.
1119
-
1120
- Deployment notes: with `bun build --compile`, ship `build/client/` (including `_prerender/`) alongside the binary — or pass it via `--asset`. On Cloudflare, upload `build/client/` as static assets so the platform serves prerendered files before the worker runs.
1121
-
1122
- ---
1123
-
1124
- ## 22. Single-binary deployment (`bun build --compile`)
1125
-
1126
- BractJS compiles to a single executable. Because `bun build --compile` can't trace runtime fs scans or dynamic `import(absPath)`, a codegen step materializes routes, layouts, actions, and the manifest into static imports so the binary boots with **zero filesystem reads of `appDir`**.
1127
-
1128
- ### One-shot
1129
-
1130
- ```sh
1131
- bractjs compile ./myapp
1132
- # = codegen:registry → build → codegen:manifest → bun build --compile app/server.ts
1133
- ```
1134
-
1135
- ### The `app/server.ts` entry
1136
-
1137
- The scaffold includes:
1138
-
1139
- ```ts
1140
- import { createServer } from "@bractjs/bractjs";
1141
- import { routeFiles, moduleRegistry } from "./_generated/routes.ts";
1142
- import { actionModules } from "./_generated/actions.ts";
1143
- import { manifest } from "./_generated/manifest.ts";
1144
-
1145
- createServer({
1146
- port: Number(process.env.PORT ?? 3000),
1147
- appDir: "./app",
1148
- publicDir: "./public",
1149
- manifest, // no manifest read from disk
1150
- routeFiles, // no Bun.Glob route scan
1151
- moduleRegistry, // no dynamic import(absPath)
1152
- actionModules, // no scan/import for "use server" files
1153
- });
1154
- ```
1155
-
1156
- When all four are present, the server uses the pre-imported modules for routing, layouts, actions, and assets.
1157
-
1158
- ### Manual pipeline
1159
-
1160
- ```sh
1161
- bractjs codegen:registry # A — scan routes/actions → static imports
1162
- bractjs build # B — client + server bundles + manifest
1163
- bractjs codegen:manifest # C — embed manifest as a TS constant
1164
- bun build --compile app/server.ts \ # D — single binary
1165
- --asset build/client/ --outfile ./myapp
1166
- ```
1167
-
1168
- `--asset build/client/` embeds JS/CSS into the binary (true single file); omit it to ship `myapp` + `build/client/` side by side.
1169
-
1170
- The codegen functions are exported: `writeModuleRegistries(appDir)`, `writeManifestModule(appDir, buildDir)`, and the lower-level `generateRouteRegistry` / `generateActionRegistry` / `generateManifestModule`.
1171
-
1172
- > **Contributor note — keep the binary working:** anything on the server request/startup path must avoid runtime `Bun.Glob`/computed-path `import()`, must fall back from `realpath()` to `Bun.file().exists()` for embedded assets, and must preserve every consumed export when projecting route modules. Two tests enforce this: `src/__tests__/compile-safety.test.ts` (fast static scan) and `src/__tests__/compile-smoke.test.ts` (compiles and boots a real binary).
1173
-
1174
- ---
1175
-
1176
- ## 23. Custom adapters
1177
-
1178
- The server core is adapter-agnostic. The default is `BunAdapter` (wraps `Bun.serve`); supply your own via `createServer({ adapter })`.
1179
-
1180
- ```ts
1181
- import type { BractAdapter } from "@bractjs/bractjs";
1182
- import { BunAdapter } from "@bractjs/bractjs";
1183
-
1184
- // BractAdapter: { fetch(req): Promise<Response>; listen?(port): void }
1185
- ```
1186
-
1187
- **Cloudflare Workers:**
1188
- ```ts
1189
- import { buildFetchHandler, makeCloudflareHandler } from "@bractjs/bractjs";
1190
- const handler = buildFetchHandler({ appDir: "./app", manifest });
1191
- export default makeCloudflareHandler(handler);
1192
- // or createCloudflareAdapter(handler) for the BractAdapter-compatible form
1193
- ```
1194
-
1195
- ---
1196
-
1197
- ## 24. Build plugins
1198
-
1199
- If you write your own `Bun.build()` (instead of `bractjs build`), you **must** apply these or face crashes / secret leaks. All are exported.
1200
-
1201
- | Bundle | Plugin | Without it |
1202
- |---|---|---|
1203
- | Server | `useClientStubPlugin` | Server crashes calling browser-only hooks from `"use client"` modules. |
1204
- | Client | `createUseServerProxyPlugin(appDir)` | Server-action bodies (DB code, secrets) ship in the browser JS. |
1205
- | Client | `serverModuleStubPlugin` | `*.server.ts` source (DB drivers, secrets) leaks into the client bundle. |
1206
- | Client | `clientEnvPlugin(allowedKeys, env)` | Server env vars leak into the browser bundle. |
1207
- | Client | `cssModulesPlugin` | `*.module.css` imports don't resolve. |
1208
-
1209
- ```ts
1210
- import {
1211
- useClientStubPlugin, createUseServerProxyPlugin,
1212
- serverModuleStubPlugin, clientEnvPlugin, cssModulesPlugin,
1213
- } from "@bractjs/bractjs";
1214
-
1215
- // Server bundle (target: "bun"):
1216
- plugins: [useClientStubPlugin];
1217
-
1218
- // Client bundle (target: "browser"):
1219
- plugins: [
1220
- serverModuleStubPlugin,
1221
- createUseServerProxyPlugin("./app"), // same appDir as createServer!
1222
- clientEnvPlugin(["PUBLIC_API_URL"], Bun.env as Record<string, string>),
1223
- cssModulesPlugin,
1224
- ];
1225
- ```
1226
-
1227
- > Always pass the **same `appDir`** to `createUseServerProxyPlugin` that you pass to `createServer` — action IDs hash the appDir-relative path, so a mismatch makes every `/_action` return 404. `transformCssModule(filePath)` is exported for custom CSS pipelines; `useServerProxyPlugin` is the legacy absolute-path variant. `serverModuleStubPlugin` stubs `*.server.ts` exports so a route can import a server module inside its loader/action without leaking source; `serverOnlyPlugin` is the stricter predecessor that hard-fails such imports instead (still exported for opt-in use).
1228
-
1229
- ---
1230
-
1231
- ## 25. Configuration reference
1232
-
1233
- All fields optional. Wrap the default export in `defineConfig()` for autocomplete + type-checking (it's a no-op identity helper), or pass these to `createServer` / `createDevServer` / `runBuild`.
1234
-
1235
- ```ts
1236
- import { defineConfig } from "@bractjs/bractjs";
1237
- export default defineConfig({ port: 3000, clientEnv: ["PUBLIC_API_URL"] });
1238
- ```
1239
-
1240
- | Field | Type | Default | Description |
1241
- |-------|------|---------|-------------|
1242
- | `port` | `number` | `3000` | TCP port |
1243
- | `hmrPort` | `number` | `3001` | Dev HMR WebSocket port (`bractjs dev` only) |
1244
- | `appDir` | `string` | `"./app"` | Contains `routes/` and `root.tsx` |
1245
- | `publicDir` | `string` | `"./public"` | Static assets (served no-cache) |
1246
- | `buildDir` | `string` | `"./build"` | Build output |
1247
- | `imageCacheDir` | `string` | `".bract-image-cache"` | Optimized-image disk cache |
1248
- | `sourcemap` | `string` | `"external"` | `"none" \| "linked" \| "inline" \| "external"` |
1249
- | `minify` | `boolean` | `true` | Minify client bundles |
1250
- | `clientEnv` | `string[]` | `[]` | `process.env` keys exposed to the client |
1251
- | `plugins` | `BunPlugin[]` | `[]` | Extra client-build plugins |
1252
- | `adapter` | `BractAdapter` | `BunAdapter` | Custom server adapter |
1253
- | `i18n` | `I18nConfig` | — | Locale config consumed by the i18n utilities |
1254
- | `ssr` | `boolean` | `true` | `false` → SPA mode: static shell for every document GET (§21) |
1255
- | `prerender` | `string[] \| () => paths` | — | Paths to prerender at build time (§21) |
1256
- | `onStart` / `onShutdown` / `onError` | hooks | — | Lifecycle (§16) |
1257
-
1258
- `loadUserConfig()` validates these shapes and throws a clear error on an obvious mistake (e.g. a string `port`).
1259
-
1260
- ---
1261
-
1262
- ## 26. Full export index
1263
-
1264
- Everything importable from `@bractjs/bractjs` ([src/index.ts](src/index.ts)):
1265
-
1266
- **Server / runtime:** `createServer`, `buildFetchHandler`, `renderRoute`, `redirect`, `json`, `error`, `defineContext`, `route`, `validate`, `safeValidate`, `isValidationResponse`, `readValidationError`, `validateSearch`, `searchParamsToObject`, `formText`, `formValues`, `defineActions`, `BunAdapter`, `defineLifecycle`, `renderSpaShell`
1267
-
1268
- **Errors:** `BractJSError`, `HttpError`, `isRedirect`, `isHttpError`, `isBractJSError`
1269
-
1270
- **Streaming:** `defer`, `Deferred`, `isDeferred`, `Await`
1271
-
1272
- **Context:** `BractJSContext`, `BractJSProvider`, `useBractJSContext`
1273
-
1274
- **Middleware:** `pipeline`, `MiddlewarePipeline`, `requestLogger`, `cors`, `authGuard`, `csp`, `getCspNonce`, `CSP_NONCE_KEY`
1275
-
1276
- **Sessions:** `createCookieSession`
1277
-
1278
- **Components:** `Outlet`, `Link`, `Form`, `Scripts`, `LiveReload`, `Await`, `Image`, `ScrollRestoration`
1279
-
1280
- **Hooks:** `useLoaderData`, `useActionData`, `useLocation`, `useParams`, `useNavigation`, `useNavigate`, `useFetcher`, `useFetchers`, `useRevalidator`, `useSearch`, `useSetSearch`, `useSearchParams`, `useBlocker`, `useLocale`, `useLocalizedLink`
1281
-
1282
- **Search serialization:** `serializeSearch`
1283
-
1284
- **i18n:** `wrapRoutesWithLocale`, `stripLocale`, `localizedDataPath`
1285
-
1286
- **Client RPC:** `createClient`
1287
-
1288
- **Build / programmatic:** `createDevServer`, `runBuild`, `loadUserConfig`, `defineConfig`, `runPrerender`
1289
-
1290
- **Codegen:** `writeModuleRegistries`, `writeManifestModule`, `generateRouteRegistry`, `generateActionRegistry`, `generateManifestModule`
1291
-
1292
- **Build plugins:** `useClientStubPlugin`, `createUseServerProxyPlugin`, `useServerProxyPlugin`, `serverModuleStubPlugin`, `serverOnlyPlugin`, `clientEnvPlugin`, `cssModulesPlugin`, `transformCssModule`
1293
-
1294
- **Adapters:** `createCloudflareAdapter`, `makeCloudflareHandler`
1295
-
1296
- **Types:** `LoaderArgs`, `ActionArgs`, `MetaArgs`, `MetaDescriptor`, `LoaderFunction`, `ActionFunction`, `MetaFunction`, `RouteModule`, `RouteDefinition`, `RouteFile`, `Segment`, `RouterLocation`, `ShouldRevalidateArgs`, `ShouldRevalidateFunction`, `BractJSConfig`, `RenderOptions`, `ServerManifest`, `ContextFactory`, `ApiRouteDefinition`, `AppApiRoutes`, `FieldErrors`, `ValidationError`, `BractAdapter`, `LifecycleHooks`, `MiddlewareFn`, `MiddlewareContext`, `CorsOptions`, `AuthGuardOptions`, `CspOptions`, `SessionStorageLike`, `SessionLike`, `Session`, `SessionStorage`, `SessionData`, `CookieSessionOptions`, `CommitOptions`, `ImageProps`, `ImageFormat`, `ImageFit`, `SearchParamsResult`, `SetSearchFn`, `SetSearchOptions`, `SearchOutputFor`, `InferSchemaOutput`, `LoaderData`, `ActionData`, `SafeValidateResult`, `FetcherResult`, `FetcherEntry`, `FetcherState`, `FetcherFormProps`, `UseFetcherOptions`, `Revalidator`, `ScrollRestorationProps`, `PrerenderOptions`, `PrerenderResult`, `I18nConfig`, `DevServerOptions`, `DevServer`, `BuildConfig`, `CodegenResult`, `ModuleRegistry`, `BractJSContextValue`, `RouteManifest`
1297
-
1298
- ---
1299
-
1300
- ## 27. Security model
1301
-
1302
- BractJS ships secure defaults, but a few behaviors are worth understanding so you don't accidentally widen your attack surface.
1303
-
1304
- - **What `"use server"` publishes.** Every exported **function** of a `"use server"` module becomes an unauthenticated RPC endpoint reachable via `POST /_action` and `GET /_stream`. In files under `routes/`, framework exports (`loader`, `action`, `default`, `meta`, `beforeLoad`, `context`, `ErrorBoundary`, `Fallback`, `config`, `searchSchema`, `ssr`) are **not** registered as actions — but any *other* exported function is. Treat each exported action as a public endpoint: **do your own authorization inside the function body** (read the session, check the user). The CSRF gate only proves the call is same-origin; it does not authenticate the user.
1305
- - **`/_stream` calls actions with no arguments.** A streaming action invoked over `GET /_stream` receives no caller input. It must be safe to call with none and must authorize itself.
1306
- - **CORS + credentials.** Listing an origin in `cors({ origin: [...], credentials: true })` fully trusts that origin for credentialed cross-origin reads. Only list origins you control. `credentials:true` with `origin:"*"` is refused at setup. Never add `X-BractJS-Action` to `Access-Control-Allow-Headers` — it is the CSRF gate.
1307
- - **Error messages.** In production, loader/action errors are surfaced to the client as a generic message; the real message + stack appear only in dev (`NODE_ENV=development`). For user-facing structured errors throw an `HttpError` (its message *is* shown) — never put secrets in a raw `Error.message`.
1308
- - **CSP `style-src`.** The opt-in `csp()` middleware nonces all scripts, but its default `style-src` includes `'unsafe-inline'` for ergonomics. Pass `csp({ strict: true })` (or override `style-src` with a nonce/hash) if you want to block inline-style injection.
1309
- - **Already handled for you:** path traversal + symlink escape on `/public` and `/_image`, open-redirect neutralization (`redirect()` requires `{ allowExternal: true }` to go off-origin), XSS-safe SSR data island (`safeStringify`), prototype-pollution rejection on action JSON bodies, request body-size caps, signed/constant-time-verified cookie sessions, and CSRF via layered `Sec-Fetch-Site` + custom-header + `Origin` checks.
1310
-
1311
- ---
1312
-
1313
- ## Changelog
1314
-
1315
- See [CHANGELOG.md](CHANGELOG.md) for release history.
1316
-
1317
- ---
1318
-
1319
- ## Why BractJS
1320
-
1321
- - **Bun-native** — `Bun.serve`, `Bun.build`, `Bun.file`, `Bun.Glob`, `Bun.watch`. No Node.js.
1322
- - **Zero framework deps** — only peers are `react` and `react-dom`.
1323
- - **Streaming SSR** — `renderToReadableStream()` with `defer()` and `<Await>`.
1324
- - **File-based routing** — drop a file in `app/routes/`.
1325
- - **Full-stack** — loaders, actions, sessions, server actions, typed API routes, middleware.
1326
- - **Typed routes** — codegen wires `<Link>`, `useNavigate`, and `useParams` to your routes (autocompleted paths, typed params), plus a type-safe URL builder.
1327
- - **Single-binary** — `bun build --compile` to one executable.
1328
-
1329
- ## License
1330
-
1331
- MIT