# @askrjs/server/middleware

> Published API exports for @askrjs/server/middleware.

Source: [https://askrjs.com/docs/reference/api/server/middleware](https://askrjs.com/docs/reference/api/server/middleware)

Status: stable. Packages: @askrjs/server/middleware.

**Published packages are authoritative.** Examples may lag behind a published contract. When guidance differs, verify the exports and TypeScript declarations in your installed package, then file an issue.

## Exports

This entrypoint publishes 17 exports from the declarations shipped by @askrjs/server.

### `accessLog`

```ts
accessLog: (logger: ResponseLogger) => Middleware
```

Creates middleware that times each request and invokes `logger` with the request, response,
duration, and (if present) request ID after the downstream chain resolves.

### `cors`

```ts
cors: (options?: CorsOptions) => Middleware
```

Creates CORS middleware that validates the request origin, answers preflight `OPTIONS`
requests with `204` and the appropriate `Access-Control-*` headers, and adds
`Access-Control-Allow-Origin`/`Vary: Origin` (plus exposed headers) to actual responses.
Genuine preflight is quota-neutral in {@link rateLimit } regardless of middleware order.

### `CorsOptions`

```ts
CorsOptions: any
```

Options for {@link cors}.

- `origin`: origin?: string | ((origin: string, context: ServerContext) => string | null);

- `methods`: methods?: readonly string[];

- `allowedHeaders`: allowedHeaders?: readonly string[];

- `exposedHeaders`: exposedHeaders?: readonly string[];

- `credentials`: credentials?: boolean;

- `maxAgeSeconds`: maxAgeSeconds?: number;

### `createCsrfToken`

```ts
createCsrfToken: (secret: string, sessionId: string) => Promise<string>
```

Creates a CSRF token bound to a session ID, as an HMAC-SHA256 signature encoded base64url.

### `createMemoryRateLimitStore`

```ts
createMemoryRateLimitStore: (options?: MemoryRateLimitStoreOptions) => RateLimitStore
```

Creates an in-memory {@link RateLimitStore} backed by a `Map`, suitable for single-process
deployments. Expired keys are pruned before capacity eviction, then the least recently used key
is evicted when `maxEntries` is reached. Eviction forgets that key's current quota; use a custom
store when the key space is adversarial or cannot be safely bounded for one process.

### `csrf`

```ts
csrf: (options: CsrfOptions) => Middleware
```

Creates middleware that enforces CSRF protection on state-changing requests (all methods
except `GET`/`HEAD`/`OPTIONS`/`TRACE`) by requiring a valid token bound to the current
session, supplied via a request header or (for form-encoded bodies) a form field.

### `CsrfOptions`

```ts
CsrfOptions: any
```

Options for {@link csrf}.

- `secret`: readonly secret: string;

- `sessionId`: readonly sessionId?: (context: Parameters<Middleware>[0]) => string | undefined;

- `header`: readonly header?: string;

- `formField`: readonly formField?: string;

### `enforceHttps`

```ts
enforceHttps: (options?: { trustProxy?: boolean; status?: 301 | 302 | 307 | 308; }) => Middleware
```

Creates middleware that redirects non-HTTPS requests to their HTTPS equivalent.

### `MemoryRateLimitStoreOptions`

```ts
MemoryRateLimitStoreOptions: any
```

Options for {@link createMemoryRateLimitStore}.

- `now`: readonly now?: () => number;

- `maxEntries`: Maximum active keys retained in memory. Defaults to 10,000.

### `rateLimit`

```ts
rateLimit: (options: RateLimitOptions) => Middleware
```

Creates middleware that enforces a request-rate limit per key (e.g. per client), adding
`RateLimit-*` response headers and returning `429 Too Many Requests` with `Retry-After`
when the limit is exceeded. Genuine CORS preflight requests (`OPTIONS` with both `Origin`
and `Access-Control-Request-Method`) are quota-neutral regardless of middleware order.

### `RateLimitOptions`

```ts
RateLimitOptions: any
```

Options for {@link rateLimit}.

- `store`: readonly store?: RateLimitStore;

- `limit`: readonly limit: number;

- `windowMs`: readonly windowMs: number;

- `key`: Returns an application-trusted bucket identity. Proxy headers are
intentionally never interpreted by this middleware.

- `now`: readonly now?: () => number;

### `RateLimitStore`

```ts
RateLimitStore: any
```

Pluggable backing store for {@link rateLimit}, tracking request counts per key/window.

- `consume`: consume(key: string, limit: number, windowMs: number): Promise<{
    readonly remaining: number;
    /** Epoch milliseconds at which the current window resets. */
    readonly reset: number;
    readonly allowed: boolean;
  }>;

### `requestId`

```ts
requestId: (options?: { header?: string; generate?: () => string; }) => Middleware
```

Creates middleware that reads a request ID from an incoming header (generating one if
absent), stores it on `ctx.state.requestId`, and echoes it back on the response header.

### `ResponseLogger`

```ts
ResponseLogger: (entry: {
  request: Request;
  response: Response;
  durationMs: number;
  requestId?: string;
}) => void
```

Callback invoked by {@link accessLog} with details of a completed request.

### `securityHeaders`

```ts
securityHeaders: (options?: { contentSecurityPolicy?: string | ((context: ServerContext) => string); referrerPolicy?: string; frameOptions?: string; }) => Middleware
```

Creates middleware that adds standard security headers to every response:
`X-Content-Type-Options: nosniff`, `Referrer-Policy`, `X-Frame-Options`, and (if configured)
`Content-Security-Policy`.

### `trace`

```ts
trace: (start: (context: ServerContext) => void | (() => void | Promise<void>)) => Middleware
```

Creates middleware that invokes `start` at the beginning of each request and, if it returns
a function, invokes that function after the downstream chain settles (success or throw) —
e.g. to open and close a tracing span around the request.

### `verifyCsrfToken`

```ts
verifyCsrfToken: (secret: string, sessionId: string, token: string) => Promise<boolean>
```

Verifies a CSRF token against a session ID using an HMAC-SHA256 signature.

## Documentation navigation

[Previous](https://askrjs.com/docs/reference/api/server/http/index.md) | [Next](https://askrjs.com/docs/reference/api/server/askr/index.md)
