> [Agent navigation index](/llms.txt)

# Server authentication and security

Protect explicit routes with typed authentication and adapt Brix's secure response defaults without weakening them accidentally.

Start with a working `brixServer` from [server foundations](/docs/server-foundations.md) and an
application-owned session or identity service. The finished route should reject an anonymous
request, expose a typed user to its handler, and still return Brix's default security headers.

## Authenticate explicit routes

Applications that sign in through the brix-auth authorization server use the framework-owned policy
in [sign in with brix-auth](/docs/server-brix-auth.md) instead of writing this middleware. For any other
identity source, define the authenticated Hono context once, in `src/brix.server.ts`. In this
example, `User` and `sessions` are your application's user type and session service:

`src/brix.server.ts`

```ts
"use server";

import { defineBrixAuth, defineBrixServer } from "brix/server";
import type { Context } from "brix/hono";
import { brix } from "./brix.ts";
import { env } from "./env.server.ts";
import { sessions, type User } from "./features/sessions/sessions.server.ts";

type AuthContext = Context<{ Variables: { user: User } }>;

const auth = defineBrixAuth<AuthContext>(async (c, next, redirectUrl) => {
  const user = await sessions.user(c.req.raw);
  if (!user) {
    return redirectUrl ? c.redirect(redirectUrl) : c.json({ error: "Unauthorized" }, 401);
  }
  c.set("user", user);
  await next();
});

export const brixServer = defineBrixServer(brix, { env, auth });

```

Keep the generated route-factory exports below this definition. `defineBrixServer` infers the
authenticated context from `auth`, so protected routes receive it without repeating generics.

Authentication runs only on routes that opt in. Keep the choice visible beside each route:

```ts
export const updateProfileApiRoute = createApiRoute(updateProfileApiContract, {
  auth: true,
  handler: async (c, { body }) => {
    const user = c.get("user");
    return saveProfile(user.id, body);
  },
});

export const settingsPageRoute = createPageRoute(settingsPageContract, {
  component: SettingsPage,
  auth: { redirectUrl: (c) => `/login?return=${encodeURIComponent(c.req.url)}` },
  load: (c) => loadSettings(c.get("user").id),
});

```

- API and response routes accept `auth: true`.
- Page routes and fragments accept `auth: true` or `{ redirectUrl: (c) => string }`. The URL is
  passed to your middleware as its third argument; with `auth: true` it is `undefined`, so the
  example above answers 401. Validate any return destination in the login handler before
  redirecting to it.
- Public callbacks keep the ordinary context; protected handlers and loaders receive the narrowed one.
- Route creation fails when a route sets `auth` but `defineBrixServer` has no `auth`.

Route authentication runs after locale resolution and application middleware. A `resolveLocale`
callback cannot read the user set here; share one request-memoized session lookup with
authentication when locale comes from the session. See
[session-backed locale resolution](/docs/translations-setup.md#resolve-locale-consistently). The lookup
does not grant access: protected routes still require authentication and authorization.

This middleware establishes identity, not permission to every resource. In a protected handler,
read `c.get("user")` and check whether that user may access the requested account, booking, or
document. Never trust an incoming user-ID header unless a trusted upstream authenticates it and
removes caller-supplied values.

## Keep authenticated output private

Authenticated responses never enter shared edge caches through Brix:

- Page and fragment routes with `auth` cannot declare a `cache` policy. The combination is a type
  error and fails at route creation; use `cache: false` or omit it.
- Every route with `auth` adds `Cache-Control: private` when the response, including an
  authentication failure or redirect, has no `Cache-Control` of its own. Set a stricter value such
  as `no-store` explicitly for sensitive downloads and forms.
- `decidePageCache` and `decideFragmentCache` from `brix/edge` bypass routes whose manifest marks
  `auth`, and any request carrying an `Authorization` header, even when a hand-built manifest
  declares a policy.

Do not treat cache partitioning as authorization. Public pages that personalize output from cookies
must stay uncached or set `private`/`no-store`; edge admission rejects those responses and any
response with `Set-Cookie`.

## Protect mutations from other sites

`auth: true` establishes identity, not request intent. Before any route runs, `createBrixApp`
rejects browser requests with any method other than `GET`, `HEAD`, or `OPTIONS` that come from
another origin. The response is 403 with `Cache-Control: no-store` and JSON
`{ "error": "Forbidden" }`.

- `Sec-Fetch-Site: same-origin` or `none` passes. `same-site` and `cross-site` are rejected, so a
  sibling subdomain is treated as another origin.
- Without `Sec-Fetch-Site`, a request without `Origin` passes (webhooks, server-to-server clients),
  and an `Origin` whose host equals the request URL's host passes. A proxy that rewrites `Host`
  must preserve the public host for this fallback.
- `csrf: { trustedOrigins: [...] }` admits exact `http`/`https` origins without paths or wildcards.
  Invalid entries throw when the server is defined.
- `csrf: false` disables the guard. Use it only when an upstream enforces the same policy.
- `csrf: { exemptPaths: [...] }` exempts exact paths from the guard, for endpoints that read no
  cookies and must accept requests from any site, such as an OAuth server's token, revocation, and
  registration endpoints. Entries are paths such as `/token`: non-empty `/`-separated segments,
  none `.` or `..` (percent-encoded, such as `%2e`, either), with no `*`, query, or trailing slash;
  anything else throws when the server is defined. They are compared with the request path exactly as received, so `/token/` or
  `/%74oken` keep the guard even where the router hands them to the same route. Every other path
  keeps the guard. Never exempt a route that reads a session cookie.
- A server integration may exempt its own routes the same way when it runs a stricter check there.
  The brix-auth integration exempts exactly its [MCP endpoint](/docs/server-brix-auth.md#serve-an-mcp-server)
  and its metadata path, which read no cookies; the endpoint checks `Origin` against its own
  `allowedOrigins`.

```ts
export const brixServer = defineBrixServer(brix, {
  env,
  csrf: {
    trustedOrigins: ["https://admin.example.com"],
    exemptPaths: ["/token", "/revoke", "/register"],
  },
});

```

The guard cannot stop script already running on your own origin, and `GET`, `HEAD`, and `OPTIONS`
are never blocked, so keep those methods free of side effects. Add session-bound tokens when a flow
must resist a compromised same-origin page or very old browsers that send neither header.

Request bodies on body-schema API routes and on response routes are limited to 1 MiB
(`1_048_576` bytes) by default, and an oversized body returns 413 with JSON
`{ "error": "Request too large" }`. A declared `Content-Length` is checked before locale checks,
authentication, and parsing. API routes buffer a chunked body up to the limit at the same point.
Response routes never read a chunked body before authentication; they count bytes as the handler
reads them. Once the limit is passed the read fails, and the route responds with 413 even if the
handler catches or wraps the error. Raise or lower it
deliberately, for the application with `maxBodyBytes` on `defineBrixServer` or for one route:

```ts
export const uploadAvatarResponseRoute = createResponseRoute(uploadAvatarResponseContract, {
  auth: true,
  maxBodyBytes: 5 * 1_048_576,
  handler: (c) => storeAvatar(c),
});

```

The value must be a non-negative safe integer. Bodyless API routes do not read the body and are not
limited. See [request size and cross-origin protection](/docs/api-routes-server.md#request-size-and-cross-origin-protection)
and the [progressive form checklist](/docs/response-routes.md#progressively-enhanced-mutation-forms) for
receipt, replay, no-store, and browser verification responsibilities. Brix does not supply an
application session store or transactional duplicate-write guarantee.

## Allow cross-origin browser calls

Brix sends no CORS headers by default, so a browser application on another origin cannot read your
API responses. To allow a known frontend, add Hono's CORS middleware from `brix/hono/cors` as
application middleware, and list the same origin as a trusted CSRF origin so its mutations pass the
guard:

`src/brix.server.ts`

```ts
import { cors } from "brix/hono/cors";

const adminOrigin = "https://admin.example.com";

export const brixServer = defineBrixServer(brix, {
  env,
  csrf: { trustedOrigins: [adminOrigin] },
  middleware: [
    cors({
      origin: [adminOrigin],
      allowMethods: ["GET", "POST", "PUT", "DELETE"],
      allowHeaders: ["Content-Type", "Authorization"],
      credentials: true,
    }),
  ],
});

```

Keep allowed origins in your [environment configuration](/docs/environment.md) when they differ by
stage; with `env` configured, `cors` also accepts `origin: (origin, c) => ...` to read `c.env`.
Never reflect arbitrary origins with `credentials: true`.

Application middleware runs after the CSRF guard. An origin missing from `trustedOrigins` therefore
receives a 403 without CORS headers on mutations, which the browser reports as a CORS failure.
Preflight `OPTIONS` requests are never blocked by the guard. CORS controls which origins may read
responses; it is not authentication or authorization. The brix-auth
[MCP endpoint](/docs/server-brix-auth.md#browser-based-mcp-clients) runs before application middleware
and sets its own CORS headers, so an application-wide `cors()` does not apply there. See [cross-origin browser calls](/docs/workspaces-external.md#configure-cross-origin-browser-calls)
for the client side.

## Keep secure defaults

`createBrixApp` emits secure headers and a nonce-based Content Security Policy before application middleware. Defaults restrict resources to the application, deny objects and framing, allow inline generated styles, and authorize executable hydration through a fresh nonce and `strict-dynamic`.

Every response receives these headers by default and loses `X-Powered-By`:

- `Content-Security-Policy`: the directives listed below
- `Cross-Origin-Opener-Policy`: `same-origin` (Swagger UI routes differ, described below)
- `Cross-Origin-Resource-Policy`: `same-origin`
- `Origin-Agent-Cluster`: `?1`
- `Permissions-Policy`: `camera=(), geolocation=(), microphone=(), payment=(), usb=()`
- `Referrer-Policy`: `strict-origin-when-cross-origin`
- `Strict-Transport-Security`: `max-age=31536000; includeSubDomains`
- `X-Content-Type-Options`: `nosniff`
- `X-DNS-Prefetch-Control`: `off`
- `X-Download-Options`: `noopen`
- `X-Frame-Options`: `DENY`
- `X-Permitted-Cross-Domain-Policies`: `none`
- `X-XSS-Protection`: `0`

`Cross-Origin-Embedder-Policy` is not sent. The default CSP directives are:

- `default-src 'self'`
- `base-uri 'none'`
- `connect-src 'self'` (development adds `ws:` and `wss:` for hot reload)
- `font-src 'self' data:`
- `form-action 'self'`
- `frame-ancestors 'none'`
- `img-src 'self' data: blob:`
- `object-src 'none'`
- `script-src` with the request nonce, `'strict-dynamic'`, and the asset source
- `style-src 'self' 'unsafe-inline'` plus the asset source
- `worker-src 'self' blob:`

The asset source is `'self'` for same-origin assets, or the origin of the build prefix or
`renderer.assetPrefix`. Request-derived prefixes are resolved once for CSP and rendering together.
This does not authorize cross-origin fonts, images, or API connections; configure those directives
explicitly. See [request-aware asset delivery](/docs/server-foundations.md#select-a-production-asset-directory-per-request).

When Swagger UI is enabled with `openapi.ui: swaggerUi()`, its GET/HEAD responses use `Cross-Origin-Opener-Policy: same-origin-allow-popups`, and its OAuth callback uses `unsafe-none`, so a cross-origin authorization popup can return to its opener. Other routes and assets retain `same-origin`. Explicit opener-policy overrides and `security: false` take precedence. The UI page's `connect-src` also gains the origins of documented OAuth `tokenUrl`/`refreshUrl` and OpenID Connect discovery URLs, so Swagger can exchange tokens without widening other routes. If an edge owns headers, preserve these scoped policies; an explicit `same-origin` policy on the UI or callback breaks cross-origin OAuth popups. See [API documentation](/docs/api-documentation.md) for callback paths and provider requirements.

### Override only required directives

```ts
export const brixServer = defineBrixServer(brix, {
  env,
  security: {
    contentSecurityPolicy: {
      connectSrc: ["'self'", "https://api.example.com"],
    },
  },
});

```

This permits browser connections to one API origin without changing framing or resource-sharing
policy. Add `frameAncestors` only when the application must be embedded; the Contentful preview
integration can [scope that exception to preview](/docs/contentful-preview.md).

- Each supplied directive replaces its default; `false` removes one.
- Brix always restores the nonce in `script-src`. Markdown and plain-text responses instead receive
  `script-src 'none'` with every nonce removed, so they never carry a per-response nonce.
- A cross-origin `frameAncestors` removes the conflicting default `X-Frame-Options: DENY` unless you
  set `xFrameOptions` explicitly.
- Other `security` keys, such as `strictTransportSecurity` or `referrerPolicy`, replace that header's
  default; `false` omits it. `contentSecurityPolicyReportOnly` adds a report-only policy.
- Trusted Types is opt-in because every script must support it.

Disable CSP with `security: { contentSecurityPolicy: false }` only when an edge emits it, and use
`security: false` only when another trusted layer emits the complete secure-header policy. A BFF
cannot secure a separately hosted frontend document; configure that frontend too.

### Let an edge own CSP for cached HTML

A nonce authorizes scripts for one response only. Edge admission (`decidePageCache`) therefore
rejects HTML whose CSP carries a nonce, and application response-cache middleware must not store
rendered HTML while the default CSP is on. To cache HTML at a shared edge:

1. Disable origin CSP with `security: { contentSecurityPolicy: false }`. Brix still renders its
   executable bootstrap `script` elements with a `nonce` attribute, now empty, and module preloads
   without one.
1. On every delivery, including cache hits, generate a fresh random nonce at the edge and write it
   into each `script` element's `nonce` attribute (for example with an HTML rewriter). Add it to
   `link rel="modulepreload"` elements too.
1. Send a complete `Content-Security-Policy` with that nonce and `'strict-dynamic'` in `script-src`,
   plus the other directives your pages need. Islands and chunks loaded by the bootstrap are then
   trusted through `'strict-dynamic'`.

Never store a response after the edge has written its nonce. Fragment HTML contains no executable
inline script; the page bootstrap hydrates fragments only from modules under the page's asset prefix.
See [edge composition](/docs/fragments-composition.md) for the admission flow.

### Failure responses

Environment initialization failures retain the configured static security headers and a fresh CSP
nonce, including these opt-outs and the scoped OpenAPI opener policies. Because configuration is
unresolved, Brix omits callback-valued CSP sources (including report-only sources), dynamic asset
origins, and integration-specific security overrides on that sanitized 500 response. Static asset
origins and static directive values remain. Normal initialized requests still use those callbacks.

Test both anonymous and authenticated requests with the [route harness](/docs/testing-routes.md). Then
continue to [middleware, errors, and logging](/docs/server-runtime.md); deployment is not required to
verify this boundary.
