Skip to main content
zerotal

Documentation


Documentation / zerotal / session / CsrfMiddleware

Class: CsrfMiddleware

Defined in: packages/session/src/CsrfMiddleware.ts:58

CSRF protection middleware.

Generates a random token on first request and stores it in the session. On mutating requests (POST, PUT, PATCH, DELETE), validates that the client sent the token back via the x-csrf-token or x-xsrf-token header.

Token comparison uses a constant-time algorithm to prevent timing attacks.

Design note — why not native Bun.CSRF? Bun.CSRF issues stateless HMAC tokens, whereas this middleware deliberately uses a session-bound double-submit token: the token lives in the user's session and is mirrored into a readable XSRF-TOKEN cookie. The session binding is intentional — it ties each token to a specific authenticated session and integrates with the SPA/Inertia auto-header flow below — so we keep the session-bound scheme rather than switching to stateless tokens.

After every request it automatically sets a non-HttpOnly XSRF-TOKEN cookie so that Axios (and therefore Inertia) can read it and attach it as the X-XSRF-TOKEN header on subsequent mutating requests — zero manual config.

Register it after SessionMiddleware (it reads/writes the session). On a failed check the pipeline short-circuits with an HTTP 419 JSON response and next() is never called.

Example

// Usage order — after SessionMiddleware:
app.use(CsrfMiddleware);                        // HTTP (dev)
app.use(CsrfMiddleware.with({ secure: true })); // HTTPS (production)

// Expose the token server-side (e.g. in Inertia shared props):
Inertia.share({ csrf_token: () => CsrfMiddleware.token() });

Extends

Constructors

Constructor

new CsrfMiddleware(options?): CsrfMiddleware

Defined in: packages/session/src/CsrfMiddleware.ts:61

Parameters

options?

CsrfOptions = {}

Returns

CsrfMiddleware

Overrides

BaseMiddleware.constructor

Properties

options

protected options: CsrfOptions

Defined in: packages/session/src/CsrfMiddleware.ts:59

Subclasses must declare this with their default option values. TypeScript enforces this at compile time — forgetting it is a type error.

Overrides

BaseMiddleware.options

Methods

with()

static with<T, Opts>(this, options): () => InstanceType<T>

Defined in: packages/core/src/middleware/BaseMiddleware.ts:48

Returns a zero-arg subclass with the given options deep-merged on top of the subclass defaults, usable directly in app.use([...]).

Type Parameters

T

T extends (...args) => BaseMiddleware<any>

Opts

Opts = T extends (...args) => BaseMiddleware<U> ? U : object

Parameters

this

T

options

Partial<Opts>

Returns

() => InstanceType<T>

Inherited from

BaseMiddleware.with


afterResponse()?

optional afterResponse(ctx): Promise<void>

Defined in: packages/core/src/middleware/BaseMiddleware.ts:70

Parameters

ctx

HttpContext

Returns

Promise<void>

Inherited from

BaseMiddleware.afterResponse


onError()?

optional onError(ctx, error): Promise<void>

Defined in: packages/core/src/middleware/BaseMiddleware.ts:71

Parameters

ctx

HttpContext

error

Error

Returns

Promise<void>

Inherited from

BaseMiddleware.onError


token()

static token(ctx?): string | undefined

Defined in: packages/session/src/CsrfMiddleware.ts:128

Return the CSRF token stored in the current request's session.

Use this to embed the token in Inertia shared props or HTML meta tags. Defaults to the active request context, so it works inside a no-arg shared-prop factory.

Parameters

ctx?

HttpContext = ...

HTTP context to read the token from; defaults to the active request context via RequestContext.get.

Returns

string | undefined

The token string, or undefined if none is set (or no session).