(name → path)
// Middleware attached to a specific route
Router.middlewareFor("GET", "/dashboard"); // MiddlewareClass[]
```
## Testing
Use `HttpContext.fake()` to unit-test controllers and route handlers without a
running server:
```typescript fragment
// src/tests/PostController.test.ts
import { HttpContext } from "zerotal";
const ctx = HttpContext.fake("http://localhost/posts/42", { method: "GET" });
ctx.params = { id: "42" };
await new PostController().show(ctx);
// assert ctx.response
```
For full integration tests, boot the real app with `createTestApp()` from
`@zerotal/testing` and exercise it over real requests:
```typescript fragment
// src/tests/PostTest.ts
import { beforeAll, afterAll, it } from "bun:test";
import { createTestApp, type TestApp } from "@zerotal/testing";
import { app } from "../bootstrap/app.ts";
let testApp: TestApp;
beforeAll(async () => (testApp = await createTestApp(() => app)));
afterAll(() => testApp.close());
it("returns the post", async () => {
const post = await Post.create({ title: "Hello" });
const res = await testApp.get(`/posts/${post.id}`);
res.assertStatus(200);
res.assertJson({ title: "Hello" });
});
```
See [HTTP Tests](/docs/testing/http) for the full client and assertion surface.
## References
### Router methods
| Method | Signature | Description |
| -------------------------------------------------- | ----------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- |
| `Router.get` / `post` / `put` / `patch` / `delete` | `(path, Controller, action, mw?)` or `(path, handler, mw?)` | Register a route for an HTTP verb (controller action or closure handler). Returns a `RouteRegistration`. |
| `Router.resource` | `(name, Controller, mw?): ResourceRouteBuilder` | Register the seven RESTful routes; chain `.only()` / `.except()`. |
| `Router.view` | `(path, Component, props?, mw?): ViewRegistration` | Render a JSX view with no controller. |
| `Router.static` | `(prefix, dir, options?)` | Serve a directory of static files. |
| `Router.markdown` | `(prefix, dir, options?)` | Serve `.md` files as rendered HTML. |
| `Router.raw` | `(method, path, handler)` | Handle the raw `Request`, bypassing the middleware pipeline. |
| `Router.flow` | `(path, Page, mw?)` | Register a Flow page (added by `@zerotal/flow`). |
| `Router.group` | `(options, fn)` | Share a `prefix`, `middleware`, and/or `domain` across routes. |
| `Router.middlewareGroup` | `(name, [...])` | Define a reusable, named middleware stack. |
### Registration chaining
Every route registration returns a chainable handle:
| Chain | Signature | Effect |
| --------------------------------- | --------------------------------------------- | ---------------------------------------------------------- |
| `.name(name)` | `(name): RouteRegistration` | Name the route for `route()` URL generation. |
| `.bind(param, target)` | `(param, modelOrResolver): RouteRegistration` | Per-route model binding; overrides the global one. |
| `.maxBodySize(bytes)` | `(bytes): RouteRegistration` | Per-route request body limit; see Request body size. |
| `.withLayout(layout)` | `(layout): ViewRegistration` | Wrap a view route's output in a layout (view routes only). |
| `.only([...])` / `.except([...])` | `(actions): this` | Limit which resource actions are registered. |
### URLs, inspection and CLI
| API | Signature | Description |
| -------------------------------------- | ----------------------------------- | ----------------------------------------------------------------------- |
| `route(name, params?, query?)` | `(name, params?, query?): string` | Build a URL from a named route. Params are exact; query values go last. |
| `route.dynamic(name, params?, query?)` | `(name, params?, query?): string` | The same, for a name only known at runtime — no compile-time checking. |
| `Router.routes` / `Router.namedRoutes` | `ReadonlyMap` | Read the registered route and name maps. |
| `Router.middlewareFor(method, path)` | `(method, path): MiddlewareClass[]` | List the middleware attached to a route. |
| `HttpContext.fake(url?, init?)` | `(url?, init?): HttpContext` | Build a fake context for unit tests. |
| `bun zt route:list` | — | Print every route (`-m` method, `-p` path, `--name`, `-v` middleware). |
| `bun zt route:types` | `--check` | Write `types/routes.generated.ts`; `--check` fails when it is stale. |
## Types
| Type | What it is |
| -------------------- | --------------------------------------------------------------------------------------------------------- |
| `HttpMethod` | The verbs a route can answer on. |
| `HttpResponse` | What a handler may return when it does not write to `ctx.response`. |
| `ControllerResponse` | A controller action's return type — `void`, a `ResponseBuilder`, or a `MarkdownBuilder`. |
| `RouteParams` | The params a pattern captures, as a record. |
| `ParamsOf` | The params of one pattern, derived from the pattern string — what makes `route()` refuse a missing `:id`. |
| `RouteRegistry` | The generated name → pattern table, augmented by `types/routes.generated.ts`. |
| `RouteMiddleware` | What a route's middleware list accepts — a class, an array, or the method map. |
| `GroupOptions` | `Router.group({ prefix, middleware, domain })`. |
| `RoutingConfig` | The `routing` config namespace. |
| `FileRoutingConfig` | File-router settings within it. |
| `WebSocketHandlers` | The handler set a WebSocket route registers. |
## Next steps
- [Controllers](/docs/controllers) — move route logic out of closures.
- [Middleware](/docs/middleware) — protect and transform requests.
- [HttpContext](/docs/context) — the request/response object actions receive.
- [Multi-tenancy](/docs/tenancy) — resolve a tenant from the subdomain a group scopes to.
- [HTTP Tests](/docs/testing/http) — boot the real app and assert over requests.
---
Source: https://zerotal.dev/docs/middleware
# Middleware
Middleware sits in the HTTP pipeline between the server and your controller.
Each piece of middleware receives the request context, can inspect or modify it,
then either passes control to the next layer or short-circuits with a response.
Middleware ships in `@zerotal/core`, so there is nothing to install or register
— import the types and write a class.
## Getting Started
The middleware pipeline is built into `@zerotal/core` — nothing to install:
```typescript
import type { HttpContext, NextFn } from "zerotal";
```
## Writing middleware
Implement the `Pipe` interface — a single `handle` method that
receives the request `HttpContext` directly and reaches the request/response
helpers on it. A middleware does exactly one of three things: **continue** by
returning `next()`, **short-circuit** by returning a `Response`, or **wrap** by
awaiting `next()` (which resolves to the downstream `Response`) and returning a
transformed one. `next()` takes no arguments:
```ts
// app/middleware/LogRequestMiddleware.ts
import type { Pipe, NextFn, HttpContext } from "zerotal";
export class LogRequestMiddleware implements Pipe {
async handle(ctx: HttpContext, next: NextFn): Promise {
console.log(`→ ${ctx.request.method} ${ctx.path()}`);
const response = await next(); // ← inner middleware + controller run here
console.log(`← ${response?.status} (${ctx.took}ms)`);
return response;
}
}
```
The `Pipe` and `NextFn` types come straight from the package:
```ts
// the signatures, for reference
interface Pipe {
handle(payload: T, next: NextFn): Promise;
}
type NextFn = () => Promise;
```
### Short-circuiting
Return a `Response` without calling `next` to stop the pipeline:
```ts
// app/middleware/MaintenanceMiddleware.ts
import type { Pipe, NextFn, HttpContext } from "zerotal";
export class MaintenanceMiddleware implements Pipe {
async handle(ctx: HttpContext, next: NextFn): Promise {
if (Bun.env.MAINTENANCE_MODE === "true") {
return new Response("Down for maintenance", { status: 503 }); // ← does NOT call next
}
return next();
}
}
```
> **Note** — You can also set `ctx.response` and `return` (void) instead of returning the `Response`
> directly — both are equivalent. `ctx.response` is the canonical store; a `void` return
> leaves whatever it holds untouched, so it can never erase a response a deeper pipe set.
### Wrapping
Code after `await next()` runs on the way out — after the controller has responded. `next()`
resolves to the downstream `Response` (or `undefined` if none was produced). Use this for
saving session data or appending headers. Because some responses (e.g. `Response.redirect()`)
have immutable headers, reconstruct rather than mutate — the `withHeaders` helper does this:
```ts
// app/middleware/TimingHeaderMiddleware.ts
import type { Pipe, NextFn, HttpContext } from "zerotal";
import { withHeaders } from "zerotal";
export class TimingHeaderMiddleware implements Pipe {
async handle(ctx: HttpContext, next: NextFn): Promise {
const response = await next();
if (!response) return;
return withHeaders(response, { "Server-Timing": `total;dur=${ctx.took}` });
}
}
```
## Attaching middleware to routes
There are five ways to attach middleware. Reach for the one that matches the scope you want:
- **Per-route** — one specific route needs the middleware.
- **Route groups** — a handful of related routes share it.
- **Named groups** — the same stack (`web`, `api`) is reused across many groups.
- **File-based** (`_middleware.ts`) — every route file under a directory inherits it.
- **Auto-discovered** — a class in `app/middleware/` referenced by its name as a string.
For middleware that must run on _every_ request, see [Global middleware](#global-middleware).
### Per-route
Pass an array of middleware classes as the fourth argument to any route
registration method:
```ts fragment
// routes/index.ts
Router.get("/dashboard", DashboardController, "index", [AuthMiddleware]);
Router.post("/posts", PostController, "store", [AuthMiddleware, ThrottleMiddleware]);
```
### Route groups
```ts fragment
// routes/index.ts
Router.group({ middleware: AuthMiddleware }, () => {
Router.get("/dashboard", DashboardController, "index");
Router.resource("posts", PostController);
});
```
### Auto-discovered middleware
Middleware classes under `app/middleware/` are auto-registered at boot as a **named group under
their class name** — reference them by string in routes without importing:
```ts fragment
// app/middleware/EnsureSubscribed.ts → referenceable as "EnsureSubscribed"
Router.group({ middleware: ["EnsureSubscribed"] }, () => {
/* … */
});
```
They are **not** global by default; set `static global = true` on the class to add it to the
global pipeline. See [Conventions](/docs/conventions#middleware-appmiddleware).
### Named middleware groups
Define a group once, reference it by name everywhere:
```ts fragment
// in a ServiceProvider.onRegister()
Router.middlewareGroup("api", [ThrottleMiddleware, BearerTokenMiddleware]);
Router.middlewareGroup("web", [SessionMiddleware, CsrfMiddleware]);
```
```ts fragment
// routes/index.ts
Router.group({ prefix: "/api/v1", middleware: "api" }, () => {
Router.resource("posts", PostController);
});
Router.group({ middleware: ["web", AuthMiddleware] }, () => {
Router.get("/dashboard", DashboardController, "index");
});
```
### File-based route middleware
Drop a `_middleware.ts` file into any directory under your file routes folder.
It applies to every route file in that directory and all subdirectories:
```ts fragment
// app/routes/admin/_middleware.ts
import { AuthMiddleware } from "@zerotal/auth";
import { AdminMiddleware } from "../../middleware/AdminMiddleware.ts";
export const middleware = [AuthMiddleware, AdminMiddleware];
```
Middleware stacks from outer directories are prepended automatically —
you get `root/_middleware → admin/_middleware → route handler` in one pipeline.
> **It is `export const middleware`, an array — not `export default`.** Route
> files in the same directory default-export their handler, so a default export is
> the natural guess here and it is the wrong one. The app refuses to boot and tells
> you which file, rather than serving the subtree unguarded and looking exactly
> like a guarded one. The same applies to a `_middleware.ts` that
> fails to import: a typo or a bad import path is a boot error, not a subtree that
> quietly loses its guard. A directory with no `_middleware` file at all is the
> convention working, and stays silent.
>
> Note the asymmetry with its sibling: a `_layout` file is read by its **default**
> export, a `_middleware` file by a **named** one. Both now refuse to boot on the
> other's spelling rather than applying nothing.
## Global middleware
Register middleware that runs on every request in `bootstrap/app.ts`:
```ts fragment
// bootstrap/app.ts
export default Application.create({ providers }).use([
DevtoolsInjectionMiddleware,
RequestIdMiddleware,
]);
```
Framework providers auto-register their own middleware (e.g. `SessionMiddleware`
from `@zerotal/session`, `AuthMiddleware` from `@zerotal/auth`) — you do not need to
add them manually.
## Built-in middleware
The package ships several middleware you can drop straight into `app.use([...])`
or a route's middleware array. Each extends `BaseMiddleware`, so `.with({ … })`
bakes options into a zero-argument class.
### Names the framework already occupies
Middleware live in a flat namespace: your `app/middleware/` classes are discovered by
class name, and so are the ones a package exports. Naming one of yours after one of
these is not caught as a conflict — it surfaces later as a type error somewhere that
does not mention either file, which is a confusing way to learn that
`TwoFactorMiddleware` was taken.
The full list, so you can check before you name:
| Middleware | Package |
| -------------------------------------------------------------------------------------- | -------------------------------- |
| `CorsMiddleware`, `SecureHeadersMiddleware`, `ThrottleMiddleware`, `WebhookMiddleware` | `@zerotal/core` |
| `AuthMiddleware`, `GuestMiddleware`, `PersistUserMiddleware`, `RememberMeMiddleware` | `@zerotal/auth` |
| `BasicAuthMiddleware`, `BearerTokenMiddleware`, `JwtGuardMiddleware` | `@zerotal/auth` |
| `RequireRoleMiddleware`, `RequirePermissionMiddleware`, `TwoFactorMiddleware` | `@zerotal/auth` |
| `ValidateSignatureMiddleware` | `@zerotal/auth` |
| `SessionMiddleware`, `CsrfMiddleware`, `AuthSessionMiddleware` | `@zerotal/session` |
| `InertiaMiddleware`, `PrecognitionMiddleware` | `@zerotal/inertia` |
| `AdminGuardMiddleware`, `AdminAbilityMiddleware` | `@zerotal/admin` |
| `MonitorAuthMiddleware`, `MonitorPayloadMiddleware` | `@zerotal/monitor` |
| `IdempotencyMiddleware` | `@zerotal/cache` |
| `LocaleMiddleware` | `@zerotal/i18n` |
| `EnsureTenancyMiddleware` | `@zerotal/tenancy` |
| `TelemetryMiddleware` | `@zerotal/telemetry` |
| `BaseMiddleware` | `@zerotal/core` (the base class) |
If yours does something different from the framework's, say so in the name rather
than shadowing it — `RequireTwoFactorMiddleware` for "fence the console until staff
have enrolled" reads better than `TwoFactorMiddleware` anyway, and cannot collide.
### CorsMiddleware
```ts fragment
// bootstrap/app.ts
import { CorsMiddleware } from "zerotal";
// Permissive (default — allow any origin)
app.use([CorsMiddleware]);
// Restrict to one origin
app.use([CorsMiddleware.with({ origin: "https://app.example.com", credentials: true })]);
// Dynamic origin check
app.use([CorsMiddleware.with({ origin: (o) => o.endsWith(".mycompany.com") })]);
```
| Option | Default | Description |
| ---------------- | -------------- | ------------------------------------------------------------ |
| `origin` | `'*'` | Allowed origins — string, string[], or `(origin) => boolean` |
| `methods` | all verbs | Allowed HTTP methods |
| `allowedHeaders` | common headers | Allowed request headers |
| `exposedHeaders` | `[]` | Headers JS may read from the response |
| `credentials` | `false` | Allow cookies / auth in cross-origin requests |
| `maxAge` | `600` | Preflight cache duration (seconds) |
> **Danger** — Setting `origin: '*'` together with `credentials: true` is rejected by browsers
> and leaks cross-origin responses. Name an explicit origin (or use the function form) whenever
> you allow credentials.
### ThrottleMiddleware
Rate-limits requests with an in-memory sliding window counter. Returns `429`
with `Retry-After` and `X-RateLimit-*` headers when the limit is exceeded.
```ts fragment
// bootstrap/app.ts (global) and routes/index.ts (per-route)
import { ThrottleMiddleware } from "zerotal";
// Global: 120 requests / minute
app.use([ThrottleMiddleware.with({ maxAttempts: 120, windowSeconds: 60 })]);
// Per-route: 5 login attempts / minute
Router.post("/login", AuthController, "login", [
ThrottleMiddleware.with({ maxAttempts: 5, windowSeconds: 60 }),
]);
// By authenticated user ID instead of IP
ThrottleMiddleware.with({
maxAttempts: 1000,
windowSeconds: 3600,
keyResolver: (ctx) => String(ctx.user?.id ?? ctx.ip()),
});
```
| Option | Default | Description |
| ---------------- | ----------- | ------------------------------------- |
| `maxAttempts` | (required) | Max requests in the window |
| `windowSeconds` | `60` | Window length in seconds |
| `keyResolver` | IP address | Function returning the rate-limit key |
| `trustedProxies` | `undefined` | Number of trusted upstream proxies |
### RateLimiter — named limiters
For limits reused across routes (and queryable/resettable at runtime), define a
**named limiter** once at boot (e.g. in a `ServiceProvider`), then apply it by name.
```ts
// in a ServiceProvider (boot time)
import { RateLimiter } from "zerotal";
// 1000 req/hour per authenticated user (falls back to IP when unauthenticated)
RateLimiter.for("api").limit(1000).every(3600).byUser().register();
// 5 login attempts per minute, per IP
RateLimiter.for("login").limit(5).every(60).byIp().register();
// 500 req/min keyed by an API-key header (unknown key -> per IP)
RateLimiter.for("partner").limit(500).every(60).byApiKey("x-api-key").register();
// Custom key
RateLimiter.for("upload")
.limit(10)
.every(3600)
.by((ctx) => `user:${ctx.user?.id ?? "anon"}`)
.register();
```
Apply as route middleware with `RateLimiter.middleware(name)`:
```ts fragment
// routes/index.ts
Router.post("/login", AuthController, "login", [RateLimiter.middleware("login")]);
Router.group({ prefix: "/api", middleware: [RateLimiter.middleware("api")] }, () => {
Router.get("/users", UserController, "index");
});
```
| Method | Keys on | Falls back to |
| -------------------- | ----------------------------------------------------------------- | ------------------------ |
| `.byUser()` | `ctx.user.id` | IP when unauthenticated |
| `.byApiKey(header?)` | `x-api-key` header (or custom) | IP when header is absent |
| `.byIp()` | Socket IP, or `X-Forwarded-For` from the right (`trustedProxies`) | `'unknown'` |
| `.by(fn)` | Return value of your function | - |
Check or reset a limiter manually — e.g. clear failed login attempts after a
successful sign-in:
```ts fragment
// in a controller action — `ctx` is the HttpContext the action receives
if (await RateLimiter.tooManyAttempts("login", ctx)) {
return ctx.json({ message: "Too Many Requests" }, 429);
}
RateLimiter.resetFor("login", ctx); // clear the counter for this actor
```
> **Tip** — `ThrottleMiddleware.with({ … })` is inline and per-attachment; a named `RateLimiter`
> is defined once and can be reused, queried with `tooManyAttempts()`, and cleared with
> `resetFor()`. Use the inline form for one-off routes, the named form when the same limit
> appears in several places. See [Rate limiting](/docs/rate-limiting) for the full surface.
### SecureHeadersMiddleware
Adds `X-Frame-Options`, `X-Content-Type-Options`, `Referrer-Policy` and
`Permissions-Policy` to every response, and a `Content-Security-Policy` when you set
`contentSecurityPolicy` (Flow's guide has a
[recommended policy](/docs/flow/components#recommended-csp-header)):
```ts fragment
// bootstrap/app.ts
import { SecureHeadersMiddleware } from "zerotal";
app.use([SecureHeadersMiddleware]);
```
It is registered for you as kernel middleware, so an app gets these headers
without asking. Configure them under `app.secureHeaders` in `config/app.ts` — see
[Configuration](/docs/config-system).
**A header a route sets itself wins.** These are defaults: a response that already
carries one of them keeps its own value, and the rest are still added. So a print view
can send `Content-Security-Policy: sandbox allow-scripts` and a preview the app frames
itself can send `frame-ancestors 'self'`, while every other page gets the global policy:
```ts fragment
// app/routes/messages/[id]/print.ts
export function GET() {
return new Response(html, {
headers: { "Content-Type": "text/html", "Content-Security-Policy": "sandbox allow-scripts" },
});
}
```
**Static files get the same headers**, even though no middleware runs for them.
Files under `public/` are handed to Bun as pre-registered responses and served
without entering JavaScript, so the pipeline never sees them; the header set is
baked into those responses at registration time instead. A per-directory header
passed to `Router.static()` still wins, so a mount that is deliberately
embeddable stays that way.
> **Tip** — Run [`bun zt doctor --url=…`](/docs/deployment) after deploying. A
> header your app sets and your proxy also sets is invisible from inside the
> process, and browsers disagree about which copy applies.
### WebhookMiddleware
Verifies HMAC-SHA256 signatures on incoming webhook requests:
```ts fragment
// routes/index.ts
import { WebhookMiddleware } from "zerotal";
Router.post("/webhooks/stripe", StripeController, "handle", [
WebhookMiddleware.with({
secret: Bun.env.STRIPE_WEBHOOK_SECRET!,
header: "stripe-signature",
algorithm: "sha256",
}),
]);
```
> **Danger** — Keep the webhook `secret` in an environment variable, never hard-coded. A leaked
> secret lets anyone forge valid signatures and call your webhook endpoint.
## Middleware with constructor injection
Decorate the class with `@inject(...)`, listing its dependency tokens in
constructor order; the container resolves them and passes them in:
```ts fragment
// app/middleware/AuditMiddleware.ts
import { inject } from "zerotal";
import type { Pipe, NextFn, HttpContext } from "zerotal";
@inject(AuditLogger)
export class AuditMiddleware implements Pipe {
constructor(private logger: AuditLogger) {}
async handle(ctx: HttpContext, next: NextFn): Promise {
const response = await next();
await this.logger.record(ctx.request.method, ctx.path(), ctx.user?.id);
return response;
}
}
```
## Execution order
Middleware nests like layers of an onion: outer layers run first on the way in,
and last on the way out (after `await next()`).
```text
Kernel ← outermost: the maintenance gate, then SecureHeaders
Provider middleware ← Session, Auth, Inertia, … (registered by providers)
Global (app.use) ← CORS, Throttle, your own
Group middleware ← Router.group({ middleware })
Route middleware ← Router.get(path, C, a, [M])
Controller action ← innermost
← route mw unwind
← group mw unwind
← global mw unwind
← provider mw unwind ← session saved here
← kernel unwind
```
So middleware you add with `app.use()` already sees the session and the signed-in user. If
you register your own `SecureHeadersMiddleware` (configured with `.with()`, or a subclass), it
replaces the kernel's copy of the headers and runs where you registered it. The maintenance gate
stays in the kernel and still runs first.
## Testing
Set your suite up once as described in [Testing](/docs/testing). Middleware has
two behaviours worth proving, and they are easy to confuse: what it does when it
lets a request **through**, and what it does when it **stops** one.
**Test the stop first**, because it is the reason the middleware exists:
```typescript fragment
// tests/http/middleware.test.ts
import { test } from "bun:test";
import { createApp } from "../helpers.ts";
test("a guest is turned away from a protected route", async () => {
const app = await createApp();
const res = await app.get("/dashboard");
res.assertRedirect("/login");
await app.close();
});
```
**Then prove it lets the right request through**, otherwise a middleware that
rejects everything passes the first test perfectly:
```typescript fragment
// tests/http/middleware.test.ts
const res = await app.actingAs(user).get("/dashboard");
res.assertOk();
```
**A middleware that transforms rather than blocks** is tested through its effect.
Register a probe route in the `setup` callback — `createTestApp(bootstrap, setup)`
runs it before the server starts, so the route compiles into the router:
```typescript fragment
// tests/http/middleware.test.ts
const app = await createApp(() => {
Router.get("/probe", () => ({ locale: Context.get("locale") })).middleware([LocaleMiddleware]);
});
const res = await app.get("/probe", { "Accept-Language": "fr" });
res.assertJsonPath("locale", "fr");
```
> **Warning** — Middleware ordering is behaviour, not configuration. If auth must
> run before a rate limiter (so anonymous floods are cheap) or after it (so
> logins are throttled), write the test that fails when the order flips —
> reordering the array is a one-line change nobody reviews closely.
## References
Imported from `zerotal`.
| Member | Signature | Description |
| ---------------- | ----------------------------------------------------------------------------------- | ------------------------------------------------------------------------- |
| `Pipe` | `interface Pipe { handle(payload: T, next: NextFn): Promise }` | The contract every middleware implements (`T` is `HttpContext`). |
| `NextFn` | `type NextFn = () => Promise` | Passes control downstream; resolves to the downstream `Response`. |
| `HttpContext` | `class HttpContext` | The request context passed to `handle` — read params from `ctx.params`. |
| `withHeaders` | `withHeaders(res: Response, headers: Record): Response` | Returns a copy of `res` with headers added (safe on immutable responses). |
| `BaseMiddleware` | `class BaseMiddleware { static with(options: Partial): new () => … }` | Base class providing the `.with()` option-baking helper. |
Built-in middleware classes (`MiddlewareClass.with(options)` where noted):
| Class | Configure with | Purpose |
| ------------------------- | ----------------------------- | -------------------------------------------------- |
| `CorsMiddleware` | `.with(CorsOptions)` | Cross-origin resource sharing headers. |
| `ThrottleMiddleware` | `.with(ThrottleOptions)` | In-memory sliding-window rate limiting. |
| `SecureHeadersMiddleware` | `.with(SecureHeadersOptions)` | Security response headers (CSP, frame options, …). |
| `WebhookMiddleware` | `.with(WebhookOptions)` | HMAC signature verification for webhooks. |
Named rate limiters via `RateLimiter`:
| Method | Signature | Description |
| ---------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------- |
| `RateLimiter.for` | `for(name: string): LimiterDefinition` | Start defining a named limiter. |
| `RateLimiter.middleware` | `middleware(name: string): ThrottleMiddleware` | Get the middleware for a registered limiter. |
| `RateLimiter.tooManyAttempts` | `tooManyAttempts(name: string, ctx: HttpContext): Promise` | Record a hit and report whether the limit is hit. |
| `RateLimiter.resetFor` | `resetFor(name: string, ctx: HttpContext): void` | Clear the counter for this actor's key. |
| `LimiterDefinition.limit`/`.every` | `limit(max): this` / `every(seconds): this` | Set the window size and length. |
| `LimiterDefinition.byUser`/`.byIp`/`.byApiKey`/`.by` | `byUser(): this` / `byApiKey(header?): this` / `by(fn): this` | Choose the key strategy. |
| `LimiterDefinition.register` | `register(): this` | Register the limiter with the global registry. |
## Next steps
- [Routing](/docs/routing) — attach middleware to routes and groups.
- [Lifecycle](/docs/lifecycle) — where middleware sits in the request flow.
- [Controllers](/docs/controllers) — move route logic out of closures.
- [Rate limiting](/docs/rate-limiting) — named limiters in depth.
---
Source: https://zerotal.dev/docs/controllers
# Controllers
A controller groups related request handlers into a single class, where each
public method is an action that a route can target. Controllers are resolved
through the IoC container, so a class declaring `@inject(...)` gets its
dependencies wired up automatically.
## Basic controller
A controller is a plain class. Each action receives the request `HttpContext`
directly, reads input from it, and sets the response by calling a helper on it —
actions return `void`, not a value.
```typescript fragment
// app/controllers/PostController.ts
import type { HttpContext } from "zerotal";
import { Post } from "../models/Post.ts";
export class PostController {
async index(ctx: HttpContext): Promise {
const posts = await Post.all();
ctx.json({ posts });
}
async show(ctx: HttpContext): Promise {
const post = await Post.findOrFail(Number(ctx.params.id));
ctx.json(post);
}
async store(ctx: HttpContext): Promise {
const { title, body } = await ctx.body<{ title: string; body: string }>();
const post = await Post.create({ title, body });
ctx.json(post, 201);
}
async destroy(ctx: HttpContext): Promise {
const post = await Post.findOrFail(Number(ctx.params.id));
await post.delete();
ctx.response = new Response(null, { status: 204 });
}
}
```
Map routes to actions by passing the controller class and the action name:
```typescript fragment
// routes/index.ts
import { Router } from "zerotal";
import { PostController } from "../app/controllers/PostController.ts";
import { AuthMiddleware } from "@zerotal/auth";
Router.get("/posts", PostController, "index");
Router.get("/posts/:id", PostController, "show");
Router.post("/posts", PostController, "store", [AuthMiddleware]);
Router.delete("/posts/:id", PostController, "destroy", [AuthMiddleware]);
```
> **Note** — The fourth argument is the per-route middleware array:
> `Router.get(path, Controller, action, middleware?)`. See
> [Routing](/docs/routing) for groups, prefixes, and named routes.
## Dependency injection
A controller is constructed by `container.make()`, which auto-wires its
dependencies. Decorate the **class** with `@inject(...)`, listing the tokens in
constructor order — the container resolves each token and passes it to the
constructor:
```typescript fragment
// app/controllers/PostController.ts
import type { HttpContext } from "zerotal";
import { inject } from "zerotal";
import { CacheManager } from "@zerotal/cache";
@inject(CacheManager)
export class PostController {
constructor(private cache: CacheManager) {}
async index(ctx: HttpContext): Promise {
const posts = await this.cache.remember("posts.all", 60, () => Post.all());
ctx.json({ posts });
}
}
```
> **Warning** — `@inject` is a **class** decorator and only supports constructor
> injection. There is no parameter-level or property-level `@inject` — the tokens
> are listed on the class and matched to constructor parameters by position.
### Which should I use?
- **Facades** — reach for these first for one-off lookups. No constructor wiring,
resolved from request-scoped storage on demand.
- **`@inject(...)` on the class** — when the controller depends on a service for
most of its actions and you want it injected once at construction.
### Resolving via facades
Facades are the lightest-weight option — no constructor wiring needed. They read
the current request from `AsyncLocalStorage`, so they work anywhere in the async
tree:
```typescript
// app/controllers/DashboardController.ts
import type { HttpContext } from "zerotal";
import { Cache } from "@zerotal/cache";
import { Auth } from "@zerotal/auth";
export class DashboardController {
async index(ctx: HttpContext): Promise {
const user = Auth.user(); // resolved from AsyncLocalStorage
const stats = await Cache.get("stats");
ctx.json({ user, stats });
}
}
```
## Model binding
A route parameter whose name matches an auto-registered model is bound without any
declaration — the resolved instance arrives on `ctx.params` under the param's name,
or you can read it explicitly with `ctx.model()`. `.bind()` and the model's own
`resolveRouteBinding` are for overriding that default:
```typescript fragment
// routes/index.ts — :post already resolves through Post
Router.get("/posts/:post", PostController, "show");
```
```typescript fragment
// app/controllers/PostController.ts — via ctx.params:
async show(ctx: HttpContext<{ post: Post }>): Promise {
ctx.json(ctx.params.post);
}
// app/controllers/PostController.ts — or via ctx.model():
async show(ctx: HttpContext): Promise {
const post = ctx.model("post");
ctx.json(post);
}
```
> **Note** — If the bound record is not found, the resolver throws a 404
> automatically — no guard needed. `ctx.model()` throws if no binding was
> registered for that param name.
## FormRequest validation
Delegate validation to a `FormRequest` class for cleaner controllers. The class
comes from `@zerotal/validator`:
```typescript
// app/requests/posts/StorePostRequest.ts
import { FormRequest, RuleBuilder } from "@zerotal/validator";
export class StorePostRequest extends FormRequest {
// Do NOT annotate the return type — validate() infers the typed shape from it.
// (Pipe-strings like "required|string" are Flow's @validate syntax; FormRequest
// uses the RuleBuilder.)
rules(r: RuleBuilder) {
return {
title: r.string().min(3).max(255),
body: r.string().min(10),
tags: r.array(r.string()).optional(),
};
}
}
```
`StorePostRequest.validate()` parses the request body, runs the rules, and
returns the validated data fully typed from your `rules()` return — it throws a
validation error on failure:
```typescript fragment
// app/controllers/PostController.ts
import { StorePostRequest } from "../requests/posts/StorePostRequest.ts";
async store(ctx: HttpContext): Promise {
const data = await StorePostRequest.validate(); // throws on validation failure
const post = await Post.create(data);
ctx.json(post, 201);
}
```
> **Tip** — Do not annotate the `rules()` return type explicitly. The static
> `validate()` infers the result shape from `ReturnType`, so an explicit
> annotation would widen the result back to `Record`.
See the [Validator](/docs/validator) guide for the full rules reference.
## Resource controllers
A resource controller implements the standard seven RESTful actions:
```typescript
// app/controllers/ArticleController.ts
import type { HttpContext } from "zerotal";
export class ArticleController {
async index(ctx: HttpContext): Promise {
/* GET /articles */
}
async create(ctx: HttpContext): Promise {
/* GET /articles/create */
}
async store(ctx: HttpContext): Promise {
/* POST /articles */
}
async show(ctx: HttpContext): Promise {
/* GET /articles/:id */
}
async edit(ctx: HttpContext): Promise {
/* GET /articles/:id/edit */
}
async update(ctx: HttpContext): Promise {
/* PUT /articles/:id */
}
async destroy(ctx: HttpContext): Promise {
/* DELETE /articles/:id */
}
}
```
Register all seven with a single call, or narrow them with `.only()` / `.except()`:
```typescript fragment
// routes/index.ts
Router.resource("articles", ArticleController);
Router.resource("articles", ArticleController).only(["index", "show"]);
Router.resource("articles", ArticleController).except(["create", "edit"]);
```
> **Tip** — Generate either shape with `bun zt make:controller` — add
> `--resource` for the full CRUD stubs.
## Returning responses
Controllers set `ctx.response` via helper methods — they do not return a value
(the return type is `Promise`):
```typescript fragment
// in a controller action
ctx.json(data); // 200 JSON
ctx.json(data, 201); // 201 JSON
ctx.view(MyComponent, props); // full HTML document from a view component
ctx.html("fragment
"); // raw HTML, no DOCTYPE
ctx.redirect("/dashboard", 303); // redirect (default 302)
ctx.back(); // redirect to a same-origin Referer, else "/"
```
See the [Responses](/docs/responses) guide for the full API.
## Single-action controllers
For an action that doesn't need grouping, give the controller a single method
and name it when you register the route — a file route function works equally
well:
```typescript
// app/controllers/HealthCheckController.ts
import type { HttpContext } from "zerotal";
import { Router } from "zerotal";
export class HealthCheckController {
async handle(ctx: HttpContext): Promise {
ctx.json({ status: "ok", uptime: Math.floor(process.uptime()) });
}
}
Router.get("/health", HealthCheckController, "handle");
```
## Accessing the authenticated user
With `@zerotal/auth` installed, the authenticated user is available at
`ctx.user` after `AuthMiddleware` runs. The `Auth` facade exposes the same data
from anywhere in the async tree — handy inside services called by the controller:
```typescript fragment
// in a controller action
import { Auth } from "@zerotal/auth";
async store(ctx: HttpContext): Promise {
// Via ctx (optional — undefined for guests):
const userId = ctx.user?.id;
// Via the facade (throws ForbiddenError when not authenticated):
const user = Auth.user();
const id = Auth.id(); // number
}
```
> **Note** — `ctx.user` and the `Auth` facade are contributed by
> `@zerotal/auth`, not core. See [Authentication](/docs/authentication).
## After-response work
Register a callback to run after the response has been sent — useful for
expensive side effects that shouldn't block the client. `afterResponse` returns
`this`, so it chains:
```typescript fragment
// in a controller action
async store(ctx: HttpContext): Promise {
const post = await Post.create(data);
ctx.json(post, 201);
ctx.afterResponse(async () => {
await NotifyFollowersJob.dispatch({ postId: post.id });
await Cache.forget("posts.all");
});
}
```
> **Note** — An error thrown inside an `afterResponse` callback is logged and
> swallowed; it never crashes the server or affects the already-sent response.
## References
Controller actions interact with the request through the `ctx` object
(`HttpContext`). The members used most often from a controller:
| Member | Signature | Description |
| -------------------------------------- | --------------------------- | ------------------------------------------------------------------------------------------- |
| `ctx.params` | `Record` | Route params, plus resolved model bindings under their name (e.g. `/posts/:id` → `{ id }`). |
| `ctx.body()` | `() => Promise` | Parse and cache the JSON / form request body. |
| `ctx.input(key, fallback?)` | `(key, fallback?) => T` | Read from route params → cached body → query, in order. |
| `ctx.model(name)` | `(name) => T` | The route-model-bound instance for a param; throws if unbound. |
| `ctx.json(data, status?)` | `(data, status?) => void` | Set a JSON response (default 200). |
| `ctx.view(component, props?, status?)` | overloaded | Render a view component to a full HTML document. |
| `ctx.html(markup, status?)` | `(markup, status?) => void` | Set a raw HTML response (no DOCTYPE). |
| `ctx.redirect(url, status?)` | `(url, status?) => void` | Set a redirect response (default 302). |
| `ctx.back(status?)` | `(status?) => void` | Redirect to a same-origin `Referer`, else `/`. |
| `ctx.afterResponse(cb)` | `(cb) => this` | Run work after the response is sent. |
Container wiring for controllers:
| Member | Signature | Description |
| -------------------- | --------------- | ---------------------------------------------------------------------------- |
| `@inject(...tokens)` | class decorator | Declare constructor dependencies in order; auto-wired by `container.make()`. |
## Next steps
- [Routing](/docs/routing) — map URLs to controller actions and bind models.
- [Middleware](/docs/middleware) — protect and transform requests before they reach actions.
- [Validator](/docs/validator) — the rules reference for `FormRequest` validation.
- [Responses](/docs/responses) — the full response helper API.
- [Container](/docs/container) — how `@inject` and `make()` resolve your services.
- [HttpContext](/docs/context) — the full request/response object reference.
---
Source: https://zerotal.dev/docs/context
# Requests Context
Every route handler and every middleware receives one argument: the request
`HttpContext`. There is no separate request object — the incoming `Request` is a
property on the context (`ctx.request`), and everything you'd reach for to read it
hangs off the same argument. It holds the raw request, the response being built,
the matched route params and resolved model bindings (on `ctx.params`), and the
helpers for reading input and shaping the reply.
```typescript
// in a controller
import type { HttpContext } from "zerotal";
export class PostController {
async show(ctx: HttpContext) {
return ctx.json({ id: ctx.params.id });
}
}
```
You rarely construct one yourself — the framework creates it per request, stores it
in request-scoped (`AsyncLocalStorage`) storage, and hands it to your code. For
tests, build one with [`HttpContext.fake()`](#testing).
## Destructuring the context
Every method on the context is bound to its instance, so you can destructure
exactly what a handler needs — methods included — without losing `this`:
```typescript fragment
// routes: Router.get('/posts/:post/:tab', PostController, 'show')
async show({ view, params: { post, tab } }: HttpContext<{ post: Post; tab: string }>) {
return view(ShowPost, { post, tab });
}
```
`view` is a bound method here, `post` is a resolved model binding, and `tab` is a
raw route param — all pulled straight off the one argument. Name the whole argument
instead (`async show(ctx: HttpContext)`) when you prefer `ctx.view(...)` /
`ctx.params.post`; both styles work.
> **Warning** — Computed getters (`took`, `subdomains`) are _not_ bound methods, so
> destructuring them takes a one-time snapshot at destructure time. `took` (elapsed
> ms) in particular will be frozen — read `ctx.took` directly when you want it live.
## Typed params
`HttpContext` is generic over the shape of `params`. With no type argument,
`ctx.params` is `Record` — the raw matched segments. Pass a type
argument to describe what the route resolves, including model bindings:
```typescript fragment
// raw params only — every value is a string
async index(ctx: HttpContext) {
const page = ctx.params.page; // string | undefined
}
// typed params + a resolved model binding
async show(ctx: HttpContext<{ post: Post; tab: string }>) {
ctx.params.post; // Post (resolved binding)
ctx.params.tab; // string (raw param)
}
```
The framework hands every handler the same runtime object; the type argument is a
declaration _you_ make about what this route resolves — exactly as you'd annotate
any function parameter.
## Route-model bindings
A binding turns a raw `:param` string into a loaded model instance before your
handler runs. The framework folds the instance onto `ctx.params` under the param's
name (and exposes it via `ctx.model()`).
Usually there is nothing to declare: a param whose name matches an auto-registered
model binds on its own, so `:post` resolves through `Post` by primary key.
```typescript fragment
// routes/web.ts — :post is already bound to Post
Router.get("/posts/:post", PostController, "show");
// Declare one only to override the default — a different key, or a custom lookup:
Router.get("/posts/:post", PostController, "show").bind("post", (slug) =>
Post.query().where("slug", slug).firstOrFail(),
);
```
```typescript fragment
// in PostController — ctx.params.post is the resolved Post, not the raw id
async show(ctx: HttpContext<{ post: Post }>) {
return ctx.json(ctx.params.post);
}
// the same instance, read explicitly
async show(ctx: HttpContext) {
const post = ctx.model("post");
return ctx.json(post);
}
```
Resolution runs before the middleware pipeline, so a missing record produces a 404
rendered by the exception handler rather than a half-run handler. An unbound param
stays a raw string on `ctx.params`. The full binding surface — implicit binding,
custom resolvers, scoped bindings — lives in [Routing](/docs/routing).
## Reading input
The scalar helpers check route params first, then the query string, and coerce to
the type the method name promises. Each takes an optional fallback.
```typescript fragment
// in a controller
ctx.query("page", "1"); // string | undefined — query string only
ctx.string("sort", "asc"); // string | undefined — param then query
ctx.integer("id"); // number | undefined — param then query, parsed as int
ctx.boolean("active", false); // boolean — param then query, coerced
```
### Number parsing
`integer()` reads the param-then-query value and parses it with `parseInt(raw, 10)`.
It returns the `fallback` (or `undefined` when you pass none) in two cases: the key
is absent, or the value is not a valid integer (`NaN`). Because parsing is base-10,
`"08"` reads as `8` and a trailing-garbage value like `"42abc"` parses to `42` —
validate with a [form request](/docs/validator) when you need to reject malformed
input rather than coerce it.
```typescript fragment
// in a controller — GET /posts?page=3
ctx.integer("page"); // 3
ctx.integer("page", 1); // 3 (fallback unused)
ctx.integer("missing", 1); // 1 (absent → fallback)
ctx.integer("missing"); // undefined (absent, no fallback)
ctx.integer("count"); // GET ?count=abc → undefined (NaN → fallback)
```
### Boolean coercion
`boolean()` reads the param-then-query value and returns `true` only when it is one
of `'1'`, `'true'`, `'yes'`, or `'on'` (compared case-insensitively). Any other
present value is `false`; an absent value returns the fallback, which defaults to
`false`.
```typescript fragment
// in a controller
ctx.boolean("active"); // ?active=true / ?active=1 / ?active=ON → true
ctx.boolean("active"); // ?active=0 / ?active=no / ?active= → false
ctx.boolean("active"); // absent → false (default fallback)
ctx.boolean("active", true); // absent → true (custom fallback)
```
> **Note** — These coercion helpers are for raw string params. A param bound to a
> model holds the model instance on `ctx.params`, so read it as `ctx.params.post` or
> `ctx.model("post")`, never `ctx.integer("post")`.
### The request body
`body()` parses and caches the body (JSON, form-urlencoded, or multipart fields) so
repeated calls are free, and returns `{}` on an absent or invalid body, or on a JSON body
with no fields (a bare number, string, boolean or `null`). A JSON array is returned as
sent:
```typescript fragment
const data = await ctx.body<{ title: string; body: string }>();
```
`input()` reads a single merged value in priority order — route params → cached
body → query string — without awaiting. It reads no field from an array body:
```typescript fragment
ctx.input("id"); // route :id or ?id=
ctx.input("q", "all"); // with fallback
```
> **Warning** — `input()` only sees body data if `await ctx.body()` (or a
> [validation](/docs/validator)) ran earlier in the lifecycle; otherwise it falls through to the query
> string. For guaranteed body access, `await ctx.body()` first. Outside production, a
> call that comes back empty on a JSON or form request whose body was never read logs a
> warning naming the key, once per route.
Read a header with `header()` (case-insensitive) or pull a Bearer token with
`bearerToken()`:
```typescript fragment
ctx.header("x-forwarded-for"); // string | null
ctx.bearerToken(); // string | null — strips the "Bearer " prefix
```
### Uploaded files
`file()` returns the first `UploadedFile` for a form field (or `null`); `files()`
returns all of them. Both parse and cache the multipart body on first call. A body over the
limit is refused before this runs; to let one route take a larger upload, see
[Request body size](/docs/routing#request-body-size).
```typescript fragment
const avatar = await ctx.file("avatar"); // UploadedFile | null
const attachments = await ctx.files("attachments"); // UploadedFile[]
```
A list of files can arrive as `attachments`, `attachments[]` or `attachments[0]`,
`attachments[1]`, …, depending on how the client built the form. A browser's multiple-file
input uses the first and the Inertia adapter's form helper uses the second, so
`files("attachments")` reads all three, in the order they were sent, and `file()` returns
the first of them.
An `UploadedFile` describes the upload and knows how to persist itself. Validate
before storing, then hand it a disk — `store()` returns the stored path:
```typescript fragment
// in a controller — single file
const avatar = await ctx.file("avatar");
if (avatar) {
avatar.originalName; // original filename as sent by the browser
avatar.size; // bytes
avatar.mimeType; // MIME type, e.g. 'image/jpeg'
avatar.extension(); // 'jpg', 'png', etc.
const valid = avatar.isValid({
maxSize: 2 * 1024 * 1024, // 2 MB
mimes: ["image/jpeg", "image/png"],
});
const path = await avatar.store("avatars", Storage.disk("s3"));
}
```
```typescript fragment
// in a controller — multiple files
for (const file of await ctx.files("attachments")) {
await file.store("uploads", Storage.disk());
}
```
> **Danger** — `originalName` is supplied by the client and may be untrusted.
> `store()` defaults to a `.` filename precisely so attacker-controlled
> names never reach your filesystem — sanitise the original before displaying it.
See [Storage](/docs/storage) for configuring the disks `store()` writes to.
## Building the response
The response helpers set `ctx.response` for you and return nothing — they are
terminal. You can also `return` a value from a controller; see
[Responses](/docs/responses) for the full set.
```typescript fragment
ctx.json({ user }); // 200 application/json
ctx.json({ errors }, 422); // custom status
ctx.view(WelcomeView, { name }); // full HTML document (prepends )
ctx.html("fragment
"); // HTML fragment, no DOCTYPE
ctx.redirect("/dashboard"); // 302
ctx.redirect("/dashboard", 303); // 303 — use after POST/PUT/DELETE
ctx.back(); // redirect to the Referer (same-origin only)
ctx.back(303); // same, with a 303 status
```
`view()` accepts either pre-rendered markup, or a **view component plus its props**.
A view component receives the request `HttpContext` first and your props second:
```typescript fragment
// resources/views/Welcome.tsx
export default function Welcome(ctx: HttpContext, { title }: { title: string }) {
return (
{title}
{ctx.url.pathname}
);
}
// in a controller
ctx.view(Welcome, { title: "Hello" });
```
Route params and model bindings reach the component through `ctx.params`; the second
argument is strictly the props you pass. `markdown()` renders a Markdown string to a
full HTML document via `Bun.markdown.html()`.
> **Danger** — `back()` falls back to `/` whenever the `Referer` is missing or points
> to a different origin, preventing open-redirect attacks through a forged `Referer`
> header. Don't replace it with a raw `redirect(referer)`.
## Middleware
Middleware is a class with a `handle(ctx, next)` method. It receives the same
`HttpContext` and either calls `next()` to pass control down the pipeline or
short-circuits by producing a response:
```typescript
// app/middleware/EnsureActive.ts
import type { HttpContext, NextFn } from "zerotal";
export class EnsureActive {
async handle(ctx: HttpContext, next: NextFn): Promise {
if (!ctx.boolean("active")) return ctx.redirect("/inactive");
return next();
}
}
```
Handlers and middleware now receive the exact same object, so there's a single
mental model and a single way to read params. See [Middleware](/docs/middleware) for
the pipeline, ordering, and registration.
## The authenticated user
`ctx.user` is **not** a built-in field. When `PersistUserMiddleware` (from
[`@zerotal/auth`](/docs/authentication)) runs, it reads the session's user id, loads
the matching record, and assigns it to `ctx.user`; `AuthMiddleware` reads it to guard
routes. It is `undefined` for guests.
```typescript fragment
if (!ctx.user) throw new UnauthorizedError();
return ctx.json({ email: ctx.user.email });
```
The resolver that loads the user from the session id is configured from your
registered auth model — see [Authentication](/docs/authentication).
## Client IP
```typescript fragment
ctx.clientIp(); // string | null — the client, behind however many proxies you run
ctx.ip(); // string | null — the TCP peer, from Bun's server.requestIP()
```
`clientIp()` is the one to record and to limit on. With no `app.throttle.trustedProxies` it is the
socket address. With `trustedProxies: n` it reads `X-Forwarded-For` from the right: each proxy
appends the address it received the request from, so the `n`-th entry from the end is the client
and everything to its left is whatever the client chose to send. It is the same rule the
throttles, the audit trail, the sign-in lockout and Flow use, so an address you store and the
address they limit on agree. It returns `null` when the request offers no address.
`ip()` is the peer, and behind a reverse proxy the peer is the proxy. It returns `null` when no
Bun server reference was injected (e.g. in unit tests created with `HttpContext.fake()`).
> **Warning** — `X-Forwarded-For` is written by the client as well as by your proxies. Never key
> on its leftmost entry, and do not read it yourself with `ctx.header()`: set
> `app.throttle.trustedProxies` once and call `clientIp()`.
## URL & matching helpers
```typescript fragment
ctx.path(); // "/posts" — pathname only
ctx.fullUrl(); // "https://app.test/posts?page=2"
ctx.host(); // "app.test"
ctx.is("/admin/*"); // glob match against the path (* excludes /, ** includes it)
ctx.subdomain("tenant"); // string | null — from Router.group({ domain })
ctx.subdomains; // { tenant: "acme" }
```
`isJson()` / `wantsJson()` inspect the `Content-Type` / `Accept` headers — handy in
an exception handler, or anywhere one route serves both browsers and API clients:
```typescript fragment
// in a controller or middleware
if (ctx.wantsJson()) {
ctx.json({ message: "Unauthorized" }, 401);
} else {
ctx.redirect("/login", 303);
}
```
## Flash data
Flash writes a value to the session for the **next** request only — ideal for
post-redirect success and error messages. It requires `SessionMiddleware` and
silently no-ops without it.
```typescript fragment
// before redirecting
ctx.flash("success", "Post saved!");
return ctx.redirect("/posts", 303);
```
```typescript fragment
// on the next request
const msg = ctx.flashed("success"); // 'Post saved!'
```
The redirect response builders (`redirect().withSuccess(...)`) wrap this pattern more
fluently — see [Responses](/docs/responses).
## After-response callbacks
Register work to run **after** the response has been sent — fire-and-forget side
effects that shouldn't delay the client. `afterResponse()` returns `this`, so calls
chain.
```typescript fragment
ctx.afterResponse(async () => {
await analytics.track(ctx.requestId, ctx.url.pathname);
});
```
A callback's errors are logged and swallowed, so one failure never affects the
response or the other callbacks.
> **Note** — `afterResponse()` acquires the request-scoped container reference
> synchronously at registration time, so the scope cannot be flushed before your
> callback gets a chance to run.
## Accessing the context anywhere
You don't have to thread `ctx` through every function. From anywhere in the async
call chain, `request()` returns the current request's `HttpContext`:
```typescript
import { request } from "zerotal";
request(); // the HttpContext — throws outside a request
request("page", "1"); // shorthand for request().input("page", "1")
```
The rule is two lines: take `ctx` where it's handed to you (handlers, hooks,
middleware); call `request()` anywhere else. Code that also runs **outside** a
request — a service shared with CLI commands or queue workers — uses
`HttpContext.tryGet()`, which returns `undefined` instead of throwing.
## Asking once per request
`RequestContext.remember(key, factory)` runs `factory` at most once per request
for a given key and hands every later caller the same answer:
```typescript fragment
import { RequestContext } from "zerotal";
const settings = await RequestContext.remember(`household:${id}:settings`, () =>
Settings.query().where("household_id", id).first(),
);
```
This is the other half of the [N+1 detector](/docs/database#n1-detection): the
detector tells you a query ran too many times, and when the answer is the same
every time, "ask once" is the fix rather than eager loading.
Two behaviours are deliberate, and both are the ones a hand-rolled version
usually gets wrong:
- **The promise is cached, not the resolved value.** Cache after the `await` and
a `Promise.all` of ten readers all miss — none has resolved when the others
look. Caching the promise makes the first caller's in-flight work the answer
for the other nine.
- **A rejected promise is evicted.** Otherwise one transient failure poisons
every later read in the same request, including the retry.
Outside a request it is a pass-through. A queue worker has no request to scope
to, and quietly sharing a value across jobs would be worse than not caching.
`RequestContext.forget(key)` drops a value when a write invalidates a read taken
earlier in the same request.
## Testing
`HttpContext.fake()` builds a context without a live server — perfect for unit
testing controllers and middleware:
```typescript fragment
const ctx = HttpContext.fake("http://localhost/posts?page=2", {
method: "GET",
headers: { Authorization: "Bearer token" },
});
await new PostController().index(ctx);
expect(ctx.response?.status).toBe(200);
```
Pass a `body` to exercise handlers that read one, and assign `ctx.params` directly
when the handler expects route params a real match would have provided:
```typescript fragment
// in a test — a POST with a JSON body
const ctx = HttpContext.fake("http://localhost/posts", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ title: "Hello", body: "World" }),
});
ctx.params = { id: "42" };
```
The signature is `HttpContext.fake(url?, init?, container?)`; all three are optional.
See [Testing](/docs/testing) for the full harness, and
[HTTP testing](/docs/testing/http) for the higher-level request helpers.
## References
### `HttpContext`
```typescript fragment
class HttpContext = Record> {
constructor(request: Request, container: ScopedResolver);
}
```
The per-request object every handler and middleware receives. `TParams` types
`ctx.params` — defaulting to `Record` (raw params), or the bag of
raw params and resolved model bindings you declare for a route.
#### Properties
| Property | Type | Description |
| ----------- | ----------------------- | ------------------------------------------------------------ |
| `request` | `Request` | The raw Bun/Web API `Request` object. |
| `response` | `Response \| undefined` | Set by handlers; read by the framework to send the reply. |
| `url` | `URL` | Parsed URL (`pathname`, `searchParams`, `origin`, …). |
| `params` | `TParams` | Route params, plus resolved model bindings under their name. |
| `requestId` | `string` | UUID generated per request (`crypto.randomUUID()`). |
| `startedAt` | `number` | `performance.now()` timestamp captured at construction. |
| `locale` | `string` | Current locale (default `'en'`); set by `I18nMiddleware`. |
| `took` | `number` (getter) | Whole milliseconds elapsed since `startedAt`. |
| `container` | `ScopedResolver` | The request-scoped container for this request. |
#### Input methods
| Method | Signature | Description |
| ------------- | ---------------------------------------- | ------------------------------------------------ |
| `query` | `(key, fallback?): string \| undefined` | Read a query-string param. |
| `string` | `(key, fallback?): string \| undefined` | Read a param then query as a string. |
| `integer` | `(key, fallback?): number \| undefined` | Read a param then query, parsed base-10. |
| `boolean` | `(key, fallback = false): boolean` | Coerce a param/query to a boolean. |
| `input` | `(key, fallback?): T` | Merged read: params → cached body → query. |
| `body` | `(): Promise` | Parse and cache the request body. |
| `header` | `(key, fallback = null): string \| null` | Read a request header (case-insensitive). |
| `bearerToken` | `(): string \| null` | Extract the `Authorization: Bearer` token. |
| `file` | `(field): Promise` | First uploaded file for a form field. |
| `files` | `(field): Promise` | All uploaded files for a form field. |
| `model` | `(name): T` | Resolved route-model binding; throws if unbound. |
#### Response methods
| Method | Signature | Description |
| ---------- | -------------------------------------------- | --------------------------------------------------- |
| `json` | `(data, status = 200): void` | Set a JSON response. |
| `view` | `(componentOrMarkup, props?, status?): void` | Render a full HTML document (``). |
| `markdown` | `(content, options?, status = 200): void` | Render Markdown to a full HTML page. |
| `html` | `(markup, status = 200): void` | Set a raw HTML fragment (no DOCTYPE). |
| `redirect` | `(url, status = 302): void` | Set a redirect (`301 \| 302 \| 303 \| 307 \| 308`). |
| `back` | `(status = 302): void` | Redirect to the same-origin `Referer`, else `/`. |
#### Request, session & lifecycle methods
| Method | Signature | Description |
| --------------- | -------------------------- | ------------------------------------------------------ |
| `path` | `(): string` | Request pathname (no query). |
| `fullUrl` | `(): string` | Full URL including query string. |
| `host` | `(): string` | Host portion of the URL. |
| `is` | `(pattern): boolean` | Glob-match the path (`*` excludes `/`, `**` includes). |
| `subdomain` | `(name): string \| null` | A single subdomain param from a `domain` group. |
| `isJson` | `(): boolean` | True when the body is `application/json`. |
| `wantsJson` | `(): boolean` | True when `Accept` includes `application/json`. |
| `ip` | `(): string \| null` | Socket-level client IP, or `null`. |
| `clientIp` | `(): string \| null` | Client IP behind your proxies; see Client IP. |
| `flash` | `(key, value): void` | Write a value to the session for the next request. |
| `flashed` | `(key): T \| undefined` | Read a value flashed in the previous request. |
| `afterResponse` | `(callback): this` | Run a callback after the response is sent. |
#### Static methods
| Method | Signature | Description |
| -------- | ---------------------------------------- | ----------------------------------------------------- |
| `tryGet` | `(): HttpContext \| undefined` | The active context, or `undefined` outside a request. |
| `fake` | `(url?, init?, container?): HttpContext` | Build a context for unit tests. |
> **Note** — `requestId` is echoed back to the client in the `X-Request-Id` response
> header by [`LoggerMiddleware`](/docs/logger), not by the framework core. The id
> itself always exists on the context.
### `UploadedFile`
Returned by `file()` and `files()`.
| Member | Signature | Description |
| ---------------- | ------------------------------------------------------------------------------------------ | ------------------------------------- |
| `originalName` | `originalName: string` | Client-supplied filename (untrusted). |
| `mimeType` | `mimeType: string` | Browser-reported MIME type. |
| `size` | `size: number` | File size in bytes. |
| `extension` | `extension(): string` | Lowercase extension without the dot. |
| `isValid` | `isValid(options?: FileValidationOptions): boolean` | Check `maxSize` / `mimes` rules. |
| `store` | `store(directory: string, disk: StorageDisk, filename?: string): Promise` | Write to a disk, returns the path. |
| `storeAndGetUrl` | `storeAndGetUrl(directory: string, disk: StorageDisk, filename?: string): Promise` | Store and return the public URL. |
## Next steps
- [Controllers](/docs/controllers) — where the context is most often used.
- [Validator](/docs/validator) — validate the input you read here, with `FormRequest`.
- [Responses](/docs/responses) — the full response-building API.
- [Middleware](/docs/middleware) — how the context flows through the pipeline.
- [Routing](/docs/routing) — route params and route-model binding.
- [Storage](/docs/storage) — the disks `UploadedFile.store()` writes to.
---
Source: https://zerotal.dev/docs/responses
# Responses
Controllers and middleware build the outgoing response by calling helper methods
on the per-request `HttpContext`. After your action returns, the pipeline reads
the context's `response` and sends it to the client.
In a route handler you receive the request `HttpContext` directly — name it `ctx`
— and call `ctx.json(...)`, `ctx.view(...)`, `ctx.redirect(...)`, and friends.
Middleware receives the same context and uses the identical methods.
> **Note** — Handlers and middleware receive the same `HttpContext` object. Every
> helper below works on it; `ctx` is just the variable name used throughout.
## Getting Started
Responses are built into `@zerotal/core` — nothing to install. Every handler
receives an `HttpContext` carrying the helpers below:
```typescript
import type { HttpContext } from "zerotal";
```
## JSON
```typescript fragment
// in a controller
ctx.json(data); // 200 OK — Content-Type: application/json
ctx.json(data, 201); // 201 Created
ctx.json({ errors }, 422); // 422 Unprocessable Content
```
`json(data, status = 200)` serialises with `Response.json`, so anything
JSON-serialisable is accepted: plain objects, arrays, ORM models, `null`.
## HTML views
### Full document
`view()` accepts either pre-rendered markup, or a view component plus its props.
It prepends `` and sets `Content-Type: text/html`:
```typescript fragment
// in a controller
import { WelcomePage } from "../../resources/views/WelcomePage.tsx";
ctx.view(WelcomePage(ctx, { title: "Hello" })); // pre-rendered markup
ctx.view(WelcomePage, { title: "Hello" }); // component + props
ctx.view(WelcomePage, { title: "Hello" }, 201); // component, props, status
```
When you pass a component, it receives the request `HttpContext` as its first
argument and your props as its second. Route params and model bindings reach the
component through `ctx.params`.
JSX syntax needs `"jsxImportSource": "zerotal"` in your `tsconfig.json` — set
once for the whole project, and already present in scaffolded apps. See the
[View](/docs/view) guide.
> **Tip** — Passing the component form (`ctx.view(WelcomePage, props)`) lets the
> framework hand the component the `HttpContext` for you, so you can read route
> params and model bindings from `ctx.params` without wiring them up by hand.
### Raw HTML
For htmx, Turbo Streams, or any partial render — no DOCTYPE prepended:
```typescript fragment
// in a controller
ctx.html('Saved!
');
ctx.html(renderPartial(data), 200);
```
### Markdown
Render a Markdown string to a full HTML page using Bun's built-in
`Bun.markdown.html()`. Tables, strikethrough, tasklists, autolinks, and heading
IDs are enabled by default:
```typescript fragment
// in a controller
const content = await Bun.file("./docs/guide.md").text();
ctx.markdown(content);
ctx.markdown(content, { title: "Getting Started", headings: { ids: true } });
```
When no `title` option is given, the first heading in the document is used,
falling back to `"Docs"`.
## Redirects
```typescript fragment
// in a controller
ctx.redirect("/dashboard"); // 302 Found
ctx.redirect("/dashboard", 303); // 303 See Other ← use after POST/PUT
ctx.redirect("/dashboard", 301); // 301 Permanent
ctx.redirect("/dashboard", 307); // 307 Temporary (preserves method)
ctx.redirect("/dashboard", 308); // 308 Permanent (preserves method)
ctx.back(); // 302 to Referer (safe — same origin only)
ctx.back(303); // 303 to Referer
```
`back()` reads the `Referer` header and falls back to `/` when it is missing or
points to a different origin.
> **Tip** — POST-Redirect-GET: use `303` after mutating actions so browsers
> always issue a `GET` on the redirect target and form re-submission is
> prevented.
> **Danger** — `back()` only follows a `Referer` on the same origin; a
> cross-origin or forged value falls back to `/`. This prevents open-redirect
> attacks — never bypass it by reading the header yourself.
## File downloads
Return a `Response` directly with the appropriate headers:
```typescript fragment
// in a controller
const file = Bun.file("./exports/report.csv");
ctx.response = new Response(file as unknown as BodyInit, {
headers: {
"Content-Type": "text/csv",
"Content-Disposition": 'attachment; filename="report.csv"',
},
});
```
## Custom responses
Set `ctx.response` to any `Response` object — the pipeline sends it verbatim:
```typescript fragment
// in a controller
ctx.response = new Response("pong", { status: 200 });
ctx.response = new Response(JSON.stringify({ ok: true }), {
status: 200,
headers: { "Content-Type": "application/json", "X-Custom": "value" },
});
// Stream a large body
const stream = new ReadableStream({ ... });
ctx.response = new Response(stream, {
headers: { "Content-Type": "text/event-stream" },
});
```
## Appending headers to any response
Every helper assigns a fresh `Response` to `ctx.response`. To add a header,
rebuild it from the existing one:
```typescript fragment
// in a controller, after setting ctx.response via any helper
const existing = ctx.response!;
const headers = new Headers(existing.headers);
headers.set("X-Request-Id", ctx.requestId);
ctx.response = new Response(existing.body, {
status: existing.status,
headers,
});
```
## Flash + redirect
Flash a message and redirect in one step — the flashed value is available via
`ctx.flashed()` on the next request. Flashing requires an active session
(see [Session](/docs/session)) and silently no-ops without one:
```typescript fragment
// in a controller
ctx.flash("success", "Post created!");
ctx.redirect("/posts", 303);
```
In [Inertia](/docs/inertia) apps use the `inertia()` helper with `back()` or
`redirect()` — no flash needed because Inertia preserves shared props across
redirects.
## Content negotiation
Use `wantsJson()` (true when the client sends `Accept: application/json`) to
respond differently based on what the client accepts:
```typescript fragment
// in a controller
async destroy(ctx: HttpContext): Promise {
await post.delete();
if (ctx.wantsJson()) {
ctx.response = new Response(null, { status: 204 });
} else {
ctx.flash("success", "Post deleted.");
ctx.redirect("/posts", 303);
}
}
```
## Router-level view shortcut
For routes that only render a view with static or request-computed props, skip
the controller entirely with `Router.view()`. A static props object is evaluated
once at registration; a factory function receives the `HttpContext` per request
and may be async:
```typescript fragment
// routes/web.ts
import { Router } from "zerotal";
Router.view("/about", AboutPage, { title: "About Us" });
Router.view("/dashboard", DashboardPage, async (ctx) => ({
user: ctx.user,
stats: await fetchStats(ctx.user!.id),
}));
```
## Which helper should I use?
- **`ctx.json()`** — API endpoints, fetch/XHR clients, Inertia validation
errors.
- **`ctx.view()`** — full server-rendered HTML pages from a JSX component.
- **`ctx.html()`** — HTML fragments for htmx or Turbo Streams (no DOCTYPE).
- **`ctx.markdown()`** — serve a `.md` file as a styled documentation page.
- **`ctx.redirect()` / `ctx.back()`** — after a mutation, or to send the user
elsewhere; pair with `flash()` for a one-request status message.
- **`ctx.response = new Response(...)`** — downloads, streams, custom status
codes (e.g. `204 No Content`), or any header set the helpers don't cover.
## Testing
Set your suite up once as described in [Testing](/docs/testing). Every request
through `TestApp` comes back as a `TestResponse`, whose assertions read as the
sentence you would have written in a comment.
**Assert the status by meaning, not by number**, so a failure says what went
wrong rather than what integer it saw:
```typescript fragment
// tests/http/posts.test.ts
import { test } from "bun:test";
import { createApp } from "../helpers.ts";
test("creating a post", async () => {
const app = await createApp();
const res = await app.actingAs(user).post("/posts", { title: "Hello" });
res.assertCreated(); // clearer than assertStatus(201)
res.assertJsonPath("data.title", "Hello");
await app.close();
});
```
`assertOk`, `assertCreated`, `assertNoContent`, `assertNotFound`,
`assertUnauthorized`, `assertForbidden`, and `assertUnprocessable` all exist —
reach for `assertStatus(n)` only when the code has no name.
**Redirects and JSON need different assertions**, and picking the wrong one is
how a broken route passes. `assertRedirect` checks the `Location` header;
`assertJson` parses the body:
```typescript fragment
// tests/http/posts.test.ts
res.assertRedirect("/posts/hello"); // 3xx + Location
res.assertJson({ id: 1, title: "Hello" }); // exact body match
res.assertJsonPath("meta.total", 25); // one path, ignoring the rest
res.assertJsonCount(3, "data"); // array length at a path
```
**Prefer `assertJsonPath` to `assertJson`** for anything with a timestamp or an
id in it. An exact-match assertion on a whole body fails every time an unrelated
field is added, which trains people to update tests without reading them.
**Headers and cookies are part of the response contract** when a client depends
on them:
```typescript fragment
// tests/http/downloads.test.ts
res.assertHeader("Content-Type", "text/csv");
res.assertHeader("Content-Disposition");
res.assertCookie("session");
res.assertCookieMissing("remember_me");
```
> **Note** — `assertSee` and `assertDontSee` check the rendered body as text.
> They are for HTML responses; on a JSON body they will happily match a substring
> inside a field name and give you a passing test that proves nothing.
## References
Response helpers on `HttpContext`:
| Method | Signature | Description |
| ----------- | -------------------------------------------------------------------- | --------------------------------------------------------------------- |
| `json` | `json(data: unknown, status = 200): void` | Serialise `data` as a JSON response. |
| `view` | `view(markup, status?)` / `view(component, props?, status?)` | Render a full HTML document (prepends ``). |
| `html` | `html(markup: string \| { toString(): string }, status = 200): void` | Send a raw HTML string with no DOCTYPE. |
| `markdown` | `markdown(content: string, options?, status = 200): void` | Render Markdown to a full HTML page via `Bun.markdown.html()`. |
| `redirect` | `redirect(url: string, status: 301\|302\|303\|307\|308 = 302): void` | Set a `Location` redirect response. |
| `back` | `back(status: 301\|302\|303\|307\|308 = 302): void` | Redirect to the same-origin `Referer`, or `/`. |
| `flash` | `flash(key: string, value: unknown): void` | Stash a value for the next request (needs a session). |
| `flashed` | `flashed(key: string): T \| undefined` | Read a value flashed in the previous request. |
| `wantsJson` | `wantsJson(): boolean` | True when `Accept` includes `application/json`. |
| `response` | `response: Response \| undefined` | The outgoing response; assign a `Response` directly for full control. |
Common status codes:
| Helper | Status | Typical use |
| ------------------------ | ------ | ------------------------------------------------ |
| `ctx.json(data)` | 200 | GET, success |
| `ctx.json(data, 201)` | 201 | POST, resource created |
| `ctx.json(null, 204)` | — | DELETE, no content (set `ctx.response` directly) |
| `ctx.json(errors, 422)` | 422 | Validation failed |
| `ctx.json(msg, 401)` | 401 | Unauthenticated |
| `ctx.json(msg, 403)` | 403 | Forbidden |
| `ctx.json(msg, 404)` | 404 | Not found |
| `ctx.redirect(url)` | 302 | General redirect |
| `ctx.redirect(url, 303)` | 303 | After POST/PUT/DELETE |
| `ctx.redirect(url, 301)` | 301 | Permanent redirect |
## Negotiating by client
One route, three audiences. `negotiate(ctx)` picks a branch from the `Accept` header and how the
request arrived, so a handler answers a browser, an API client and the console without three
copies of the logic:
```typescript fragment
import { negotiate } from "zerotal/http";
await negotiate(http)({
web: () => http.redirect("/dashboard"),
api: () => http.json({ ok: true }),
cli: () => http.text("done"),
});
```
`NegotiateMap` is that object; `WebContext`, `ApiContext` and `CliContext` are what each branch
receives. A missing branch falls through to `web`, because the browser is the audience most
likely to be looking.
This is what the framework's own error handler uses, which is why a 422 is a redirect-with-errors
for a form post and a JSON body for a fetch — see [Errors](/docs/errors#response-format-by-client-type).
## Next steps
- [Requests Context](/docs/context) — read input from the incoming request.
- [View](/docs/view) — render JSX and Markdown pages.
- [Inertia](/docs/inertia) — return Inertia responses for SPA frontends.
- [Cookies](/docs/cookies) — attach cookies to outgoing responses.
- [HttpContext](/docs/context) — the full per-request object these helpers live on.
---
Source: https://zerotal.dev/docs/validator
# Validation
The validator checks incoming request data against rule chains and produces
fully-typed output — no manual type assertions needed. It offers two entry
points: `FormRequest` (class-based, recommended) and the standalone `validate()`
function (for one-off use).
## Getting Started
```bash
# in your project root
bun add @zerotal/validator
```
The validator has no provider to register — import its classes and functions
directly. Database-aware rules (`unique()`, `exists()`) do require
[`DatabaseProvider`](/docs/database) to be registered; see
[Database rules](#database-rules).
## Configuration
Create `config/validator.ts` with the `ValidatorConfig()` helper so every field
stays type-checked while defaults are filled in:
```typescript
// config/validator.ts
import { ValidatorConfig } from "@zerotal/validator";
export default ValidatorConfig({
stopOnFirstFailure: true, // stop after the first failure per field
locale: "en", // default locale for error messages
});
```
| Field | Required | Default | Description |
| -------------------- | -------- | ------- | -------------------------------------------------- |
| `stopOnFirstFailure` | no | `true` | Stop validation after the first failure per field. |
| `locale` | no | `"en"` | Default locale for error messages. |
## Which entry point should I use?
- **`FormRequest`** — the default for HTTP handlers. Encapsulates rules and
authorization in a reusable, testable class, reads the request from the active
context, and throws the right error on failure.
- **`validate(ctx, factory)`** — for one-off HTTP validation where a dedicated
class would be overkill. Same failure behavior as `FormRequest`.
- **`Validator.check(data, factory)`** — for non-HTTP code (CLI commands,
services, background jobs). Returns a result object and never throws or
redirects. See [Non-HTTP validation](#non-http-validation).
## FormRequest
### Defining a request
```typescript
// app/requests/posts/StorePostRequest.ts
import { FormRequest, RuleBuilder } from "@zerotal/validator";
export class StorePostRequest extends FormRequest {
// Return true to allow, false to deny with a 403 ForbiddenError.
// Access the current request via this.context.
authorize(): boolean {
return !!this.context.user;
}
// Do NOT annotate the return type — TypeScript needs to infer the narrow shape
// for validate() to produce a typed result.
rules(r: RuleBuilder) {
return {
title: r.string().min(3).max(255),
body: r.string().min(10),
tags: r.array(r.string()).optional(),
};
}
}
```
> **Warning** — Do not add an explicit return type to `rules()`. Annotating it
> (e.g. as `Record`) widens the inferred type and makes
> `validate()` return `Record` instead of your typed shape.
### Calling validate
Call `validate()` as a static method on the class. It reads `HttpContext` from
`AsyncLocalStorage` — no arguments needed.
```typescript fragment
// in a controller
const data = await StorePostRequest.validate();
data.title; // string — fully typed, no cast needed
data.body; // string
data.tags; // string[] | undefined
```
The body is read through the same cache as [`ctx.body()`](/docs/context#the-request-body), so
the two work in either order, and after middleware that has already read the body. Afterwards
`ctx.body()` and `ctx.input()` return the body as the client sent it, not just the validated
fields. A multipart form's files are validated from the same parse that `ctx.file()` reads.
On failure, `validate()` stores `errors` and `old` (previous input) in the
session, then branches on the request type:
| Request type | Detected by | Error thrown | HTTP result |
| ------------ | ------------------------------------------------------------------------- | ------------------------- | ----------------------------------------------- |
| JSON / API | `Accept` prefers `application/json` to `text/html`, even with `X-Inertia` | `ValidationJsonError` | 422 JSON with field errors |
| Inertia | `X-Inertia: true` header, `Accept` that does not prefer JSON | `ValidationRedirectError` | Redirect back; errors surfaced via shared props |
| HTML form | neither | `ValidationRedirectError` | Redirect back; errors in session |
`Accept` prefers JSON when `application/json` has a higher q-value than `text/html`, or the same
q-value and comes first: `application/json` and `application/json, text/html` do,
`text/html, application/json` and a browser's `Accept` do not. The
[exception handler](/docs/errors) uses the same rule, so a client gets one format for a
validation error and a 404 alike. An Inertia visit sends
`Accept: text/html, application/xhtml+xml`, so it redirects; a client that keeps the
`X-Inertia` header on a call asking for JSON gets the 422 it asked for.
Both `ValidationJsonError` and `ValidationRedirectError` are exported from
`@zerotal/validator`. The exception handler renders them appropriately — you
never need to catch them yourself.
### Authorization
`authorize()` runs **before** validation. Returning `false` throws a
`ForbiddenError` (403) without touching the request body.
```typescript fragment
// in a FormRequest subclass
// Check the current user's role:
authorize(): boolean {
return (this.context.user as { role?: string })?.role === "admin";
}
// Use Gate.allows() for policy-based auth:
authorize(): boolean {
return Gate.via(PostPolicy).allows("create", new Post());
}
// Async authorize is also supported:
async authorize(): Promise {
const post = await Post.findOrFail(Number(this.context.params["id"]));
return Gate.via(PostPolicy).allows("update", post);
}
```
### Accessing context inside rules
Because `rules()` is an instance method, you have full access to `this.context`
for rules that depend on the current user, route params, or session state:
```typescript fragment
// in a FormRequest subclass
rules(r: RuleBuilder) {
const userId = this.context.user?.id;
return {
email: r.string().email()
.unique("users", "email", userId), // ignore current user on update
name: r.string().min(2).max(100),
};
}
```
### Preparing input
An HTML form cannot leave a field out or send `null`: a blank input posts `""`. A blank
optional `number()` or `date()` field already counts as absent, but a string keeps `""`, because an empty
string is a value a string field can hold. So an optional email fails on a blank input:
```typescript fragment
// in a FormRequest subclass
rules(r: RuleBuilder) {
return { assignee: r.string().trim().email().optional() };
}
```
Override `prepareForValidation()` to reshape the body before the rules see it. It runs after
`authorize()` and receives the parsed body; return the object to validate. Mutating the argument
and returning it is fine:
```typescript fragment
// in a FormRequest subclass
override prepareForValidation(body: Record) {
if (body["assignee"] === "") delete body["assignee"];
return body;
}
```
Now a blank field counts as absent. To clear a column instead, set the value to `null` and mark
the rule `.nullable()`. The default returns the body unchanged.
## Standalone validate
For simple one-off validation without a dedicated class:
```typescript fragment
// in a controller
import { validate } from "@zerotal/validator";
// validate(ctx, factory) reads the request body from the HttpContext and
// returns the validated, typed data directly. On failure it throws —
// ValidationJsonError (→ 422 JSON) or ValidationRedirectError (→ 303 back) —
// which the global exception handler turns into the right response.
const data = await validate(ctx, (r) => ({
title: r.string().min(3),
count: r.number().integer().min(1),
}));
data.title; // string — fully typed, no cast needed
data.count; // number
```
## Non-HTTP validation
For CLI commands, services, or background jobs — where there is no request to
redirect and no response to throw — use the `Validator` facade. It returns a
`{ success, data, errors }` outcome and never throws.
```typescript fragment
// in a command or service
import { Validator } from "@zerotal/validator";
const result = Validator.check(payload, (r) => ({
email: r.string().email(),
age: r.number().min(0),
}));
if (!result.success) {
console.error(result.errors);
} else {
result.data.email; // string — fully typed
}
```
## RuleBuilder types
Start every rule chain with a type method on `RuleBuilder`:
```typescript fragment
// in a rules() method or factory
const r = new RuleBuilder(); // or the `r` param in rules()
r.string(); // StringRule
r.number(); // NumberRule
r.boolean(); // BooleanRule
r.date(); // DateRule
r.file(); // FileRule — multipart/form-data uploads
r.password(); // PasswordRule — strength validation
// Convenience shorthands on RuleBuilder:
r.required(); // r.string().required() — required string, the common case
r.email(); // r.string().email()
r.url(); // r.string().url()
r.uuid(); // r.string().uuid()
r.array(r.string()); // ArrayRule — array of strings
r.object({/* … */}); // ObjectRule — nested object
```
## Common modifiers
These are available on **every** rule type:
| Method | Description |
| --------------------------------- | ---------------------------------------------------------------------------- |
| `.required(msg?)` | Field must be present and non-empty |
| `.optional()` | Field may be absent; result type becomes `T \| undefined` |
| `.nullable()` | Field may be `null` |
| `.default(val)` | Use `val` when field is absent; implies `.optional()` |
| `.sometimes()` | Only validate when field is present in input (PATCH-friendly) |
| `.bail()` | Stop after the first failing rule on this field |
| `.custom(fn)` | Run a custom sync/async function; return `true`, `false`, or an error string |
| `.requiredIf(field, value)` | Required when another field equals `value` |
| `.requiredUnless(field, value)` | Required unless another field equals `value` |
| `.requiredWith(fields[])` | Required when ANY listed field is present |
| `.requiredWithout(fields[])` | Required when ANY listed field is absent |
| `.requiredWithAll(fields[])` | Required when ALL listed fields are present |
| `.requiredWithoutAll(fields[])` | Required when ALL listed fields are absent |
| `.prohibitedIf(field, value)` | Must be absent when another field equals `value` |
| `.prohibitedUnless(field, value)` | Must be absent unless another field equals `value` |
| `.accepted()` | Truthy: `true`, `1`, `'1'`, `'yes'`, `'on'`, `'true'` |
| `.declined()` | Falsy: `false`, `0`, `'0'`, `'no'`, `'off'`, `'false'` |
### Custom validator
```typescript fragment
// in a rules() method or factory
username: r.string().custom(async (value) => {
const taken = await User.findBy("username", value as string);
return taken ? "This username is already taken." : true;
});
```
## String rules
```typescript fragment
// in a rules() method or factory
r.string()
.min(3) // minimum character length
.max(255) // maximum character length
.size(10) // exact character length
.email() // valid email address
.url() // valid URL
.uuid() // valid UUID v4
.ip() // valid IPv4 or IPv6
.json() // parseable JSON string
.regex(/^[A-Z]+$/) // matches regex
.matches(/^[A-Z]+$/, "msg") // alias for regex()
.in(["a", "b", "c"]) // value in list
.notIn(["x", "y"]) // value not in list
.alpha() // letters only (a-z, A-Z)
.alphaNum() // letters and digits
.alphaDash() // letters, digits, hyphens, underscores
.numeric() // digits only (optional leading minus)
.digits(6) // exactly 6 digits
.digitsBetween(4, 8) // between 4 and 8 digits
.startsWith("https://") // must start with prefix
.endsWith(".pdf") // must end with suffix
.trim() // strip leading/trailing whitespace (transform)
.lowercase() // convert to lowercase (transform)
.uppercase() // convert to uppercase (transform)
.confirmed() // value must equal `{field}_confirmation` in input
.sameAs("password") // value must equal another field
.present() // key must exist in input (may be empty)
.prohibited() // key must be absent from input
.password(); // semantic alias — chain constraints after this
```
## Number rules
```typescript fragment
// in a rules() method or factory
r.number()
.min(0) // minimum value (inclusive)
.max(100) // maximum value (inclusive)
.between(1, 10) // min and max in one call
.integer() // must be a whole number
.positive() // shorthand for .min(0)
.notIn([0, -1]); // value not in list
```
## Boolean rules
```typescript fragment
// in a rules() method or factory
r.boolean()
.accepted() // truthy — for "agree to terms" checkboxes
.declined(); // falsy
```
## Date rules
```typescript fragment
// in a rules() method or factory
r.date()
.after("2026-01-01") // strictly after date
.before(new Date()) // strictly before date
.afterOrEqual("2026-01-01") // on or after
.beforeOrEqual("2026-12-31"); // on or before
```
## Array rules
```typescript fragment
// in a rules() method or factory
r.array(r.string()) // array of strings
.min(1) // minimum item count
.max(10) // maximum item count
.size(3); // exact item count
r.array(r.number().integer()); // array of integers
// Nested objects in an array:
r.array(r.object({ name: r.string(), age: r.number() }));
```
## Object rules
```typescript fragment
// in a rules() method or factory
r.object({
street: r.string(),
city: r.string(),
country: r.string().in(["US", "CA", "GB"]),
zip: r
.string()
.regex(/^\d{5}$/)
.optional(),
});
```
## File rules
Validates `File` objects from `multipart/form-data` uploads:
```typescript fragment
// in a rules() method or factory
avatar: r.file()
.mimes(["jpg", "jpeg", "png", "webp"]) // allowed extensions
.max(2048) // maximum KB
.min(1) // minimum KB
.optional();
```
## Password rules
```typescript fragment
// in a rules() method or factory
r.password()
.min(8) // minimum length (default: 8)
.mixedCase() // requires upper + lower case letters
.numbers() // requires at least one digit
.symbols() // requires at least one symbol
.uncompromised() // must not contain spaces
.confirmed(); // must equal password_confirmation field
```
## Database rules
These rules require [`DatabaseProvider`](/docs/database) to be registered; they
throw at runtime otherwise.
### unique — value must not already exist in the DB
The third argument ignores a record on update — pass the current record's ID, or
a `UniqueOptions` object (`{ ignoreId }`) for clarity. A fourth argument
overrides the error message.
```typescript fragment
// in a rules() method or factory
email: r.string().email().unique("users", "email");
// Ignore the current record when updating (pass the record's ID):
email: r.string().email().unique("users", "email", this.context.user?.id);
// Equivalent, using the options object:
email: r.string().email().unique("users", "email", { ignoreId: userId });
```
### exists — value must exist in the DB
```typescript fragment
// in a rules() method or factory
userId: r.number().exists("users", "id");
roleSlug: r.string().exists("roles", "slug");
```
> **Note** — These rules stay decoupled from the ORM: `DatabaseProvider`
> registers the query executor via `registerDbRuleRunner()` during its boot, so
> `@zerotal/validator` never depends directly on `@zerotal/orm`.
## Precognition
When a request carries a `Precognition: true` header, `FormRequest.validate()`
runs the rules without executing the controller body, then short-circuits with a
`204` (no errors) or `422` (with errors). A `Precognition-Validate-Only` header
(comma-separated field names) narrows the validated set to just those fields —
useful for live, field-by-field client validation.
## Error handling
A default message names the field the way a person reads it: `first_name` is "The first name
field", whether the rule was written fluently or as a pipe string, and so are the other fields a
rule depends on ("required when card number is present"). A message you pass to a rule is used
exactly as written.
### JSON / API requests
When `Accept` prefers `application/json` to `text/html`, validation throws
`ValidationJsonError`, whether or not the request carries `X-Inertia`:
```json
{
"message": "The given data was invalid.",
"errors": {
"title": ["The title must be at least 3 characters."],
"email": ["The email has already been taken."]
}
}
```
The response is sent as `422 Unprocessable Entity`. `ExceptionHandler` catches
the error and renders this automatically.
### Inertia / HTML form requests
When `Accept` does not prefer JSON (a form post, a browser, or an Inertia visit),
validation throws `ValidationRedirectError`. `ExceptionHandler` converts this to a
redirect back to the previous page.
Errors and old input are stored in the [session](/docs/session) under the keys
`'errors'` and `'old'`. Read them on the next request:
```typescript fragment
// in a controller
const errors = ctx.flashed>("errors");
const old = ctx.flashed>("old");
```
In [Inertia](/docs/inertia), errors are passed automatically as the `errors`
prop via shared props — no manual session reading required.
## Testing
Set your suite up once as described in [Testing](/docs/testing). Validation is
worth testing at the rule level, because that is where the mistakes are and it
needs no request.
**`Validator.check()` never throws**, so a rule set tests as a pure function —
assert on the outcome rather than on a caught error:
```typescript
// tests/validation/RegisterRules.test.ts
import { test, expect } from "bun:test";
import { Validator } from "@zerotal/validator";
const rules = (r) => ({
email: r.string().email(),
age: r.number().min(18),
});
test("rejects an underage applicant", () => {
const result = Validator.check({ email: "jane@example.com", age: 17 }, rules);
expect(result.success).toBe(false);
expect(result.errors.age).toBeDefined();
});
test("returns typed data on success", () => {
const result = Validator.check({ email: "jane@example.com", age: 30 }, rules);
expect(result.success).toBe(true);
if (result.success) expect(result.data.email).toBe("jane@example.com");
});
```
**Test the values that sit either side of a boundary**, not a comfortable middle.
`age: 18` and `age: 17` prove `min(18)`; `age: 30` proves nothing that `age: 19`
would not.
**A `FormRequest` fails the HTTP request**, so test it through the route it
guards. The status tells you which failure mode you got:
```typescript fragment
// tests/http/register.test.ts
const res = await testApp.asJson().post("/register", { email: "not-an-email" });
res.assertUnprocessable().assertInvalid("email"); // 422: Accept asked for JSON
```
> **Note** — What picks the failure mode is the request's `Accept` header, not its
> body. A request whose `Accept` prefers JSON gets the `422`. Anything else is
> redirected back with the errors flashed, as a form submit is, and that includes
> `post()` without `asJson()`: it sends a JSON body with `Accept: */*`. Assert the
> shape your route actually serves;
> [HTTP Tests](/docs/testing/http#validation-whichever-shape-it-arrives-in) shows both.
**A context you build by hand works too.** `validate()` and `FormRequest` accept a plain
object holding just a `request`, and read the body straight off that request, since there
is no body cache on it to share. A failure throws the same errors as on a real context: a
`ValidationJsonError` when `Accept` prefers JSON, otherwise a `ValidationRedirectError` back
to the `Referer` when it is on the request's own origin, and to `/` when it is not. With no
session on the object, nothing is flashed. `HttpContext.fake()` gives you a real one.
## References
### RuleBuilder
| Method | Signature | Description |
| ---------- | --------------------------------------------------- | ----------------------------------------- |
| `required` | `required(message?: string): StringRule` | Required string — the common entry point. |
| `string` | `string(): StringRule` | Begin a string rule chain. |
| `number` | `number(): NumberRule` | Begin a number rule chain. |
| `boolean` | `boolean(): BooleanRule` | Begin a boolean rule chain. |
| `date` | `date(): DateRule` | Begin a date rule chain. |
| `file` | `file(): FileRule` | Validate a multipart/form-data upload. |
| `password` | `password(): PasswordRule` | Validate password strength. |
| `email` | `email(message?): StringRule` | Shorthand for `string().email()`. |
| `url` | `url(message?): StringRule` | Shorthand for `string().url()`. |
| `uuid` | `uuid(message?): StringRule` | Shorthand for `string().uuid()`. |
| `array` | `array(item: T): ArrayRule` | Array whose items match `item`. |
| `object` | `object(shape): ObjectRule` | Nested object matching `shape`. |
### Entry points
| Member | Signature | Description |
| ----------------- | -------------------------------------------- | ---------------------------------------------------- |
| `FormRequest` | `static validate(): Promise>` | Validate the active request against the class rules. |
| `FormRequest` | `authorize(): boolean \| Promise` | Allow/deny the request before validation. |
| `FormRequest` | `rules(r: RuleBuilder)` | Return the field-to-rule schema (no return type). |
| `validate` | `validate(ctx, factory): Promise>` | One-off HTTP validation; throws on failure. |
| `Validator.check` | `check(data, factory): ValidationOutcome<…>` | Non-HTTP validation; returns a result, never throws. |
## Types
| Type | What it is |
| --------------------------- | -------------------------------------------------------------------------------------------------------- |
| `ValidationErrors` | The error bag — field name to messages, which is what `withErrors()` and the `errors` shared prop carry. |
| `FieldRuleDefinition` | One field's rules as declared. |
| `InferFieldType` | The type a rule set produces, so validated data is typed rather than `unknown`. |
| `PrecognitionResponseError` | What a precognition request returns when a field fails ahead of submission. |
## Next steps
- [Requests Context](/docs/context#reading-input) — read the input that `FormRequest` validates.
- [Errors](/docs/errors) — how `ExceptionHandler` renders validation failures.
- [Authorization](/docs/authorization) — back `authorize()` with policies.
- [Database](/docs/database) — register `DatabaseProvider` for `unique()` and `exists()`.
- [Inertia](/docs/inertia) — where the `errors` shared prop comes from.
---
Source: https://zerotal.dev/docs/session
# Session
`@zerotal/session` attaches a signed, per-user data store to every HTTP request.
Read, write, flash, and regenerate session data from anywhere in the request
pipeline without managing cookies by hand.
## Getting Started
```bash
# in your project root
bun add @zerotal/session
```
## Register the provider
Add `SessionProvider` to the providers array in `bootstrap/providers.ts`:
```typescript
// bootstrap/providers.ts
import { SessionProvider } from "@zerotal/session";
export default [
// …your other providers
SessionProvider,
];
```
Registering the provider switches on the following (it only runs in the `web` and
`test` environments):
- `onRegister` — binds `session.driver` (the cookie or redis driver) and the
`session` accessor as lazy singletons in the container.
- `onBooting` — auto-registers `SessionMiddleware` via `app.useOnce()`, so the
session is loaded on every request, and warns if `session.secure` is off in
production.
- `onBooted` — pre-resolves both singletons so the `Session` facade can read them
synchronously.
> **Note** — `SessionProvider` registers only `SessionMiddleware`. CSRF protection
> is a separate middleware you opt into — see [CSRF protection](#csrf-protection).
## Configuration
Create `config/session.ts`. Use the `SessionConfig()` helper so every field stays
type-checked while supplying the defaults:
```typescript
// config/session.ts
import { SessionConfig } from "@zerotal/session";
import { env } from "zerotal";
export default SessionConfig({
driver: "cookie", // 'cookie' | 'redis'
lifetime: 86400, // seconds — 24 hours
cookie: "zerotal_session",
httpOnly: true,
sameSite: "Lax",
secure: env("APP_ENV") === "production",
secret: env("APP_KEY", ""), // signs the session cookie
});
```
| Field | Required | Default | Description |
| ---------- | -------- | ----------- | ------------------------------------------------------------ |
| `driver` | no | `"cookie"` | Storage backend: `"cookie"` or `"redis"`. |
| `lifetime` | no | `86400` | Session lifetime in seconds (24 hours). |
| `cookie` | no | `"session"` | Name of the session cookie. |
| `httpOnly` | no | `true` | Marks the session cookie HTTP-only (hidden from JS). |
| `sameSite` | no | `"Lax"` | SameSite policy: `"Strict"`, `"Lax"`, or `"None"`. |
| `secure` | no | `false` | Require HTTPS for the cookie. Turn on in production. |
| `secret` | no | `""` | HMAC secret used to sign the cookie. Set this in production. |
Add a signing secret to `.env`:
```env
# .env
APP_KEY=your-random-32-char-secret-here
```
> **Danger** — Without a strong `secret`, session cookies can be forged. The cookie
> driver throws `SessionSecretMissingError` if constructed with an empty secret;
> always set `APP_KEY` (or `session.secret`) before deploying.
## Basic usage
`SessionMiddleware` attaches a `SessionManager` to every request. There are two
ways to reach it:
- **`ctx.session`** inside a route handler — the `SessionManager` lives on the
request `HttpContext` (middleware receives the same context, so it's
`ctx.session` there too).
- **The `Session` facade** anywhere — controllers, services, jobs — without
threading the context through.
```typescript
// in a controller or service
import { Session } from "@zerotal/session";
Session.set("locale", "fr");
const locale = Session.get("locale");
Session.flash("success", "Saved!");
```
The facade resolves the current request's session via `RequestContext`, so it
works in any code running during a request. It requires `SessionMiddleware` to be
registered. Both `ctx.session` and `Session` expose the same methods (see the
[reference](#session-api) below).
## Reading and writing
```typescript fragment
// in a controller
import type { HttpContext } from "zerotal";
async action(ctx: HttpContext) {
// Write
ctx.session.set("locale", "fr");
ctx.session.set("cart", [1, 2, 3]);
// Read (returns unknown — cast to your type)
const locale = ctx.session.get("locale") as string;
const cart = ctx.session.get("cart") as number[];
// Check existence
const hasLocale = ctx.session.has("locale"); // boolean
// Read and remove in one call
const once = ctx.session.pull("cart");
// Delete one key
ctx.session.forget("locale");
// Wipe all session data
ctx.session.flush();
// Return the current session ID
const id = ctx.session.id();
}
```
Every request has a session, including the first one from a client that has no cookie yet, and
every one from a client that never keeps cookies. `ctx.session.resumed()` tells them apart: it is
`true` only when the request carried a session cookie the driver accepted, so the next request
from the same client will bring the same ID. A session started on this request, or one whose ID
was just [regenerated](#session-fixation-protection), is not resumed, and anything keyed on its ID
for a later request to find will be missed.
## Flash data
Flash stores a value for **one subsequent request only** — it is automatically
swept after the next request. The canonical use case is POST-Redirect-GET status
messages.
```typescript fragment
// in a controller — survives exactly one redirect
ctx.session.flash("success", "Post created!");
ctx.session.flash("errors", { title: ["Required"] });
// Or via the ctx shorthand (same thing):
ctx.flash("success", "Post created!");
ctx.flash("errors", { title: ["Required"] });
// Or via the Session facade (anywhere — no context needed):
Session.flash("success", "Post created!");
```
Read on the next request:
```typescript fragment
// in a controller
const msg = ctx.flashed("success");
const errors = ctx.flashed>("errors");
```
Full POST-Redirect-GET pattern:
```typescript fragment
// in a controller
async store(ctx: HttpContext) {
await Post.create(await ctx.body());
ctx.flash("success", "Post published!");
ctx.redirect("/posts", 303); // 303 ensures the browser GETs the redirect
}
async index(ctx: HttpContext) {
const success = ctx.flashed("success"); // available here, gone after
ctx.view(PostsPage, { success });
}
```
## Session fixation protection
Always regenerate the session ID after a privilege change (login, logout, password
change) to prevent session-fixation attacks:
```typescript fragment
// in a controller
ctx.session.regenerate(); // issues a new session ID; data is preserved
// or: Session.regenerate();
```
> **Danger** — Skipping `regenerate()` on login lets an attacker who planted a
> known session ID before authentication ride the now-privileged session.
## Session drivers
| Driver | Notes |
| -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
| `cookie` | Default. Session data is signed and stored in a browser cookie. No server storage needed. Max ~4 KB per session. |
| `redis` | Session data stored in Redis by ID. Use when sessions are large, shared across cluster nodes, or need server-side invalidation. Requires a Redis URL. |
### Which driver should I use?
- **`cookie`** — the default. Reach for it unless you outgrow it: it needs no
infrastructure and keeps state with the client.
- **`redis`** — switch when sessions exceed the ~4 KB cookie budget, must be shared
across multiple nodes, or need to be invalidated server-side (e.g. force-logout).
Switch drivers via the environment without changing application code:
```env
# .env.production
SESSION_DRIVER=redis
SESSION_REDIS=redis://localhost:6379
```
```typescript
// config/session.ts
import { SessionConfig } from "@zerotal/session";
import { env } from "zerotal";
export default SessionConfig({
// One of 'cookie' | 'redis', written literally: the field is that union and
// `env()` returns a plain string.
driver: "cookie",
// …
});
```
> **Note** — The redis driver reads its connection URL from the `session.redis`
> config key (defaulting to `redis://localhost:6379`). Wire it from an env var as
> shown above.
## CSRF protection
`CsrfMiddleware` defends state-changing requests against cross-site request forgery.
Unlike `SessionMiddleware`, it is **not** auto-registered — add it after the session
middleware, typically in the `web` middleware group:
```typescript fragment
// bootstrap/app.ts (or wherever you register middleware)
import { SessionMiddleware, CsrfMiddleware } from "@zerotal/session";
app.use([SessionMiddleware, CsrfMiddleware]);
// In production over HTTPS, mark the XSRF cookie Secure:
// app.use([SessionMiddleware, CsrfMiddleware.with({ secure: true })]);
```
On its first request the middleware stores a random token in the session. On any
unsafe method (anything other than `GET`, `HEAD`, `OPTIONS`) it compares — in
constant time — the session token against the `x-csrf-token` or `x-xsrf-token`
request header, returning **`419`** on a mismatch.
After every request it also sets a non-HttpOnly `XSRF-TOKEN` cookie, so Axios
(and therefore Inertia) reads it and replays it as the `X-XSRF-TOKEN` header
automatically — no manual wiring for those clients.
To expose the token elsewhere (HTML meta tag, Inertia shared props), read it with
`CsrfMiddleware.token()`:
```typescript
// in a controller or Inertia shared-props factory
import { CsrfMiddleware } from "@zerotal/session";
const token = CsrfMiddleware.token(); // reads the active request's session
```
For a plain HTML form posting via `fetch`, surface the token in a meta tag and send
it as a header:
```html
```
```typescript fragment
// in your client JS
const token = document.querySelector('meta[name="csrf-token"]')?.getAttribute("content");
fetch("/posts", {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-CSRF-Token": token ?? "",
},
body: JSON.stringify({ title: "Hello" }),
});
```
> **Warning** — The token is validated from a request **header**, not a `_token`
> form field. A classic `