> [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.

## Authenticate explicit routes

Define the authenticated Hono context once. In this example, `User` and `sessions` are
your application's user type and session service; `brix` is the browser-safe project definition:

```ts
import { defineBrixAuth, defineBrixServer } from "brix/server";
import type { Context } from "brix/hono";

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, { auth });

```

Authentication runs only on routes that opt in with `auth: true`. Protected page routes can instead provide a redirect URL callback. Keep the choice visible beside each route; public callbacks keep the ordinary context, while protected handlers receive the narrowed one. Route creation fails when `auth: true` has no configured integration.

Do not treat cache partitioning as authorization. Keep personalized page and fragment responses uncached unless your edge policy and identity model explicitly guarantee isolation.

## 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`.

Override only required directives:

```ts
export const brixServer = defineBrixServer(brix, {
  security: {
    contentSecurityPolicy: {
      connectSrc: ["'self'", "https://api.example.com"],
      frameAncestors: ["https://app.contentful.com"],
      requireTrustedTypesFor: ["'script'"],
    },
    crossOriginResourcePolicy: "cross-origin",
  },
});

```

Each supplied directive replaces its default; `false` removes one. Brix restores the nonce in `script-src`. Cross-origin `frameAncestors` removes conflicting default `X-Frame-Options: DENY` unless you set `xFrameOptions` explicitly. Trusted Types is opt-in because every script must support it.

Disable CSP 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.
