# @askrjs/server

> Published API exports for @askrjs/server.

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

Status: stable. Packages: @askrjs/server.

**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 84 exports from the declarations shipped by @askrjs/server.

### `accepted`

```ts
accepted: (value?: JsonValue, init?: ResponseInit) => Response
```

Builds a `202 Accepted` response; JSON-serializes `value` if given, otherwise an empty body.

### `accepts`

```ts
accepts: (value: string, expected: string) => boolean
```

### `AccessDeniedHandler`

```ts
AccessDeniedHandler: (decision: Extract<AuthDecision, {
  allowed: false;
}>, context: ServerContext) => Response | Promise<Response>
```

Handler invoked to produce a response when an auth decision denies access.

### `ApiRoute`

```ts
ApiRoute: any
```

A single registered route: a path/method pattern paired with a handler (or WebSocket upgrade handler).

- `path`: path: string;

- `method`: method?: string | readonly string[];

- `handler`: handler: Handler<RouteParams>;

- `upgrade`: upgrade?: WebSocketHandler<RouteParams>;

### `ApiRouteOptions`

```ts
ApiRouteOptions: any
```

Per-route configuration shared by {@link ApiRoute}.

- `auth`: auth?: AuthRequirement;

- `middleware`: middleware?: readonly Middleware<RouteParams>[];

- `maxRequestBytes`: maxRequestBytes?: number;

### `AuthCredentials`

```ts
AuthCredentials: any
```

Email/password credentials submitted to the register or authenticate endpoints.

- `email`: email: string;

- `password`: password: string;

### `AuthRouteError`

```ts
AuthRouteError: typeof AuthRouteError
```

Error thrown from `register`/`authenticate`/etc. callbacks to short-circuit an auth route with a specific status.

- `status`: readonly status: 401 | 409 | 429;

### `AuthRouteOptions`

```ts
AuthRouteOptions: any
```

Configuration for {@link registerAuthRoutes}.

- `issuer`: issuer: TokenIssuer<P>;

- `cookie`: cookie: CookieOptions & {
    name: string;
  };

- `principalSchema`: principalSchema: Schema;

- `register`: register(context: ServerContext, credentials: AuthCredentials): P | Promise<P>;

- `authenticate`: authenticate(context: ServerContext, credentials: AuthCredentials): P | null | Promise<P | null>;

- `allowAttempt`: allowAttempt(context: ServerContext, operation: "register" | "authenticate", normalizedEmail: string): boolean | Promise<boolean>;

- `revoke`: revoke?(context: ServerContext): void | Promise<void>;

- `redirect`: redirect?: (context: ServerContext, operation: "register" | "authenticate", principal: P) => string | undefined;

### `bad`

```ts
bad: (detail?: string, init?: ResponseInit) => Response
```

Alias for {@link badRequest}.

### `badRequest`

```ts
badRequest: (detail?: string, init?: ResponseInit) => Response
```

Builds a `400 Bad Request` Problem Details response.

### `bind`

```ts
bind: <T extends object = Record<string, unknown>>(context: BindContext) => Promise<T>
```

Merges a request's body, query string, and path parameters into a single object, in that
precedence order (path parameters win, then query string, then body). Supports JSON,
URL-encoded, and multipart/form-data bodies; unrecognized content types yield an empty body.

### `BindContext`

```ts
BindContext: any
```

Minimal request context required by {@link bind} to gather body, query, and path values.

- `request`: request: Request;

- `params`: params: Params;

- `url`: url: URL;

- `query`: query: URLSearchParams;

### `BindingError`

```ts
BindingError: typeof BindingError
```

Error thrown when request data cannot be bound, e.g. an unreadable or malformed body.

- `field`: readonly field?: string | undefined;

- `status`: readonly status = 400;

### `challenge`

```ts
challenge: (options?: ChallengeOptions) => Response
```

Builds a `401`/`407` Problem Details response with a `WWW-Authenticate` (or
`Proxy-Authenticate` for `407`) challenge header.

### `ChallengeOptions`

```ts
ChallengeOptions: any
```

Options for building a `WWW-Authenticate` challenge response via {@link ServerContext.challenge}.

- `scheme`: scheme?: string;

- `realm`: realm?: string;

- `status`: status?: 401 | 407;

- `detail`: detail?: string;

- `init`: init?: ResponseInit;

### `clearCookie`

```ts
clearCookie: (response: Response, name: string, options?: CookieOptions) => Response
```

Returns a clone of `response` with a `Set-Cookie` header that expires and clears `name`.

### `conflict`

```ts
conflict: (detail?: string, init?: ResponseInit) => Response
```

Builds a `409 Conflict` Problem Details response.

### `contentType`

```ts
contentType: (value: string | null) => string | undefined
```

### `CookieOptions`

```ts
CookieOptions: any
```

Options controlling how a cookie is set via {@link ServerContext.setCookie}.
Do not derive `domain` or `path` from untrusted input; invalid attribute characters are rejected.

- `domain`: ASCII cookie domain without whitespace or attribute delimiters.

- `expires`: expires?: Date;

- `httpOnly`: httpOnly?: boolean;

- `maxAge`: maxAge?: number;

- `path`: Cookie path without control characters or the `;` attribute delimiter.

- `sameSite`: sameSite?: CookieSameSite;

- `secure`: secure?: boolean;

### `CookieSameSite`

```ts
CookieSameSite: "strict" | "lax" | "none"
```

Valid values for the `SameSite` cookie attribute.

### `createCspNonce`

```ts
createCspNonce: () => CspNonceProvider
```

Creates a {@link CspNonceProvider} that lazily generates a cryptographically random,
URL-safe base64 nonce per {@link ServerContext} and caches it for the lifetime of that
context, so repeated calls within the same request return the same value.

### `created`

```ts
created: (value?: JsonValue, init?: ResponseInit) => Response
```

Builds a `201 Created` response; JSON-serializes `value` if given, otherwise an empty body.

### `createEventStream`

```ts
createEventStream: (options?: EventStreamOptions) => EventStream
```

Creates a Server-Sent Events stream backed by a `text/event-stream` `Response`, with
bounded backpressure-aware writes, optional heartbeat comments, and automatic closing when
`options.signal` aborts or `close()` is called.

### `createRouter`

```ts
createRouter: () => Router
```

Creates an empty, mutable {@link Router} with chainable HTTP-method route builders
(`get`, `post`, `put`, `patch`, `delete`, `options`, `head`, `trace`, `connect`, `ws`) and a
`use` method for registering middleware.

### `createServerApp`

```ts
createServerApp: { (router: Router): ServerApp; (options?: ServerAppOptions): ServerApp; }
```

Creates a transport-neutral server application that dispatches Web `Request`s to a
router's routes and middleware, returning Web `Response`s.

Accepts either a bare {@link Router} or a full {@link ServerAppOptions} object (which
may itself reference a router). Builds a path matcher from the combined routes, validates
request-size limits, and wraps dispatch with auth resolution, telemetry, and error handling
(payload-too-large, malformed path parameters, binding errors, and a fallback `onError`).
Creates a transport-neutral server application. See the {@link Router} overload for details.

```tsx
const app = createServerApp(router);
export default { fetch: app.fetch };
```

### `CspNonceProvider`

```ts
CspNonceProvider: (context: ServerContext) => string
```

A function that returns a CSP nonce for a given request context, stable across calls for the same context.

### `DEFAULT_MAX_REQUEST_BYTES`

```ts
DEFAULT_MAX_REQUEST_BYTES: 1048576
```

Default maximum request body size, in bytes (1 MiB), used when no limit is configured.

### `defineRoutes`

```ts
defineRoutes: (definition: (route: RouteBuilder) => void) => ApiRoute[]
```

Builds a flat list of {@link ApiRoute}s by invoking `definition` with a {@link RouteBuilder}.
Useful for defining a set of routes without a full {@link Router} (e.g. to compose into one).

### `error`

```ts
error: (status?: number, detail?: string, init?: ResponseInit) => Response
```

Builds a Problem Details error response with a configurable status (default `500`).

### `EventStream`

```ts
EventStream: any
```

A live Server-Sent Events stream, backed by a streaming `Response`.

- `response`: readonly response: Response;

- `closed`: readonly closed: Promise<void>;

- `send`: Queues an event in order. Await or otherwise handle the returned promise before producing
without bound. Rejects with `QuotaExceededError` when the pending-write limit is full.

- `comment`: Queues an SSE comment in order. Rejects with `QuotaExceededError` when the pending-write
limit is full.

- `close`: close(): Promise<void>;

### `EventStreamOptions`

```ts
EventStreamOptions: any
```

Options for {@link createEventStream}.

- `signal`: Aborting this signal closes the stream.

- `heartbeatInterval`: If set, sends a `heartbeat` comment on this interval (in ms) to keep the connection alive.

- `highWaterMark`: Backpressure threshold for the underlying `ReadableStream` and maximum number of
unresolved `send()`/`comment()` calls admitted at once. Defaults to 16.

- `headers`: headers?: HeadersInit;

### `explicitlyAccepts`

```ts
explicitlyAccepts: (value: string, expected: string) => boolean
```

### `forbidden`

```ts
forbidden: (detail?: string, init?: ResponseInit) => Response
```

Builds a `403 Forbidden` Problem Details response.

### `formatServerSentEvent`

```ts
formatServerSentEvent: (event: ServerSentEvent) => string
```

Serializes a {@link ServerSentEvent} to the `text/event-stream` wire format, escaping
multi-line data/comment fields and validating that `event`/`id` contain no line breaks.

### `Handler`

```ts
Handler: {
  bivarianceHack(context: ServerContext<RouteParams>): Response | Promise<Response>;
}["bivarianceHack"]
```

A route handler function that produces a response for a given {@link ServerContext}.

### `internalServerError`

```ts
internalServerError: (detail?: string, init?: ResponseInit) => Response
```

Builds a `500 Internal Server Error` Problem Details response.

### `json`

```ts
json: (value: JsonValue, init?: ResponseInit) => Response
```

Builds a `200 OK`-shaped JSON response, serializing `value` and setting the JSON content type.

### `JsonValue`

```ts
JsonValue: unknown
```

A value that can be serialized as JSON.

### `methodNotAllowed`

```ts
methodNotAllowed: (allow?: string | readonly string[], init?: ResponseInit) => Response
```

Builds a `405 Method Not Allowed` Problem Details response, setting the `Allow` header if given.

### `Middleware`

```ts
Middleware: {
  bivarianceHack(context: ServerContext<RouteParams>, next: Next): Response | Promise<Response>;
}["bivarianceHack"]
```

A middleware function that may short-circuit or delegate to `next` to produce a response.

### `Next`

```ts
Next: () => Response | Promise<Response>
```

Continuation function passed to a {@link Middleware}, invoking the next handler in the chain.

### `noContent`

```ts
noContent: (init?: ResponseInit) => Response
```

Builds a `204 No Content` response with an empty body.

### `notFound`

```ts
notFound: (detail?: string, init?: ResponseInit) => Response
```

Builds a `404 Not Found` Problem Details response.

### `notImplemented`

```ts
notImplemented: (detail?: string, init?: ResponseInit) => Response
```

Builds a `501 Not Implemented` Problem Details response.

### `ok`

```ts
ok: (value?: JsonValue, init?: ResponseInit) => Response
```

Builds a `200 OK` response; JSON-serializes `value` if given, otherwise an empty body.

### `Params`

```ts
Params: Record<string, string>
```

A map of route path parameter names to their string values.

### `PathParams`

```ts
PathParams: string extends Path ? Params : { [Name in PathParameterNames<Path>]: string; }
```

Infers a {@link Params}-shaped object type from a route path pattern, extracting the names
of `{param}` and `{*param}` segments as required string keys.

### `PayloadTooLargeError`

```ts
PayloadTooLargeError: typeof PayloadTooLargeError
```

Error thrown when a request body exceeds the configured maximum size.

- `status`: readonly status = 413;

### `ProbeHandler`

```ts
ProbeHandler: (context: ServerContext) => ProbeResult | Promise<ProbeResult>
```

A health-check handler used for liveness/readiness/startup probes.

### `ProbeOptions`

```ts
ProbeOptions: any
```

Optional handlers for the built-in `livez`/`readyz`/`startupz`/`targetz` health probe routes.

- `livez`: livez?: ProbeHandler;

- `readyz`: readyz?: ProbeHandler;

- `startupz`: startupz?: ProbeHandler;

- `targetz`: targetz?: ProbeHandler;

### `ProbeResult`

```ts
ProbeResult: boolean | Response | void
```

Result of a health probe: `true`/`false` for pass/fail, a `Response` to return as-is, or `void` for pass.

### `problem`

```ts
problem: (status: number, detail?: string, options?: ProblemOptions & { init?: ResponseInit; }) => Response
```

Builds an RFC 9457 `application/problem+json` response, defaulting `type` to `about:blank`
and `title` to a standard reason phrase for the given `status` (falling back to "HTTP Error").

### `Problem`

```ts
Problem: any
```

An RFC 9457 Problem Details object, as produced by {@link ServerContext.problem}.

- `type`: type: string;

- `title`: title: string;

- `status`: status: number;

- `detail`: detail?: string;

- `instance`: instance?: string;

### `ProblemOptions`

```ts
ProblemOptions: any
```

Optional fields used to customize a {@link Problem} response.

- `type`: type?: string;

- `title`: title?: string;

- `instance`: instance?: string;

- `extensions`: extensions?: Record<string, unknown>;

### `readRequestBytes`

```ts
readRequestBytes: (request: Request, maximum?: number) => Promise<Uint8Array>
```

Reads a request body into memory as raw bytes, enforcing a maximum size. The result is
cached per-request so subsequent reads (e.g. for JSON, text, or form data) reuse the same
buffered bytes instead of re-reading the stream.

### `readRequestFormData`

```ts
readRequestFormData: (request: Request, maximum?: number) => Promise<FormData>
```

Reads a request body and parses it as `multipart/form-data`, enforcing a maximum size.

### `readRequestText`

```ts
readRequestText: (request: Request, maximum?: number) => Promise<string>
```

Reads and decodes a request body as UTF-8 text, enforcing a maximum size.

### `redirect`

```ts
redirect: (location: string, status?: 301 | 302 | 303 | 307 | 308) => Response
```

Builds a redirect response with an empty body and a `Location` header. Defaults to `302 Found`.

### `registerAuthRoutes`

```ts
registerAuthRoutes: <Dependencies, P extends Principal>(api: Pick<ApiDefinition<Dependencies>, "group">, options: AuthRouteOptions<P>) => void
```

Registers a standard set of authentication routes (`POST /auth/v1/accounts`,
`GET/POST /auth/v1/session`, `DELETE /auth/v1/session`) on an OpenAPI-style API/group,
handling registration, login, session lookup, and logout with CSRF protection via a
same-origin `Origin` header check, per-attempt rate limiting, and cookie-based token storage.

### `RequestState`

```ts
RequestState: Record<string, unknown>
```

Arbitrary per-request state bag attached to a {@link ServerContext}.

### `RouteBuilder`

```ts
RouteBuilder: any
```

Chainable, per-HTTP-method route registration methods, one per method plus `ws` for WebSockets.

- `route`: route<const Path extends string>(method: string | readonly string[], path: Path, handler: Handler<PathParams<Path>>, options?: ApiRouteOptions<PathParams<Path>>): ApiRoute<PathParams<Path>>;

- `get`: get<const Path extends string>(path: Path, handler: Handler<PathParams<Path>>, options?: ApiRouteOptions<PathParams<Path>>): ApiRoute<PathParams<Path>>;

- `post`: post<const Path extends string>(path: Path, handler: Handler<PathParams<Path>>, options?: ApiRouteOptions<PathParams<Path>>): ApiRoute<PathParams<Path>>;

- `put`: put<const Path extends string>(path: Path, handler: Handler<PathParams<Path>>, options?: ApiRouteOptions<PathParams<Path>>): ApiRoute<PathParams<Path>>;

- `patch`: patch<const Path extends string>(path: Path, handler: Handler<PathParams<Path>>, options?: ApiRouteOptions<PathParams<Path>>): ApiRoute<PathParams<Path>>;

- `delete`: delete<const Path extends string>(path: Path, handler: Handler<PathParams<Path>>, options?: ApiRouteOptions<PathParams<Path>>): ApiRoute<PathParams<Path>>;

- `options`: options<const Path extends string>(path: Path, handler: Handler<PathParams<Path>>, options?: ApiRouteOptions<PathParams<Path>>): ApiRoute<PathParams<Path>>;

- `head`: head<const Path extends string>(path: Path, handler: Handler<PathParams<Path>>, options?: ApiRouteOptions<PathParams<Path>>): ApiRoute<PathParams<Path>>;

- `trace`: trace<const Path extends string>(path: Path, handler: Handler<PathParams<Path>>, options?: ApiRouteOptions<PathParams<Path>>): ApiRoute<PathParams<Path>>;

- `connect`: connect<const Path extends string>(path: Path, handler: Handler<PathParams<Path>>, options?: ApiRouteOptions<PathParams<Path>>): ApiRoute<PathParams<Path>>;

- `ws`: ws<const Path extends string>(path: Path, handler: WebSocketHandler<PathParams<Path>>, options?: ApiRouteOptions<PathParams<Path>>): ApiRoute<PathParams<Path>>;

### `Router`

```ts
Router: any
```

A mutable collection of routes and middleware, built with chainable per-method registration
methods (each returning the router itself for chaining) and a `use` method for middleware.

- `routes`: readonly routes: readonly ApiRoute[];

- `middleware`: readonly middleware: readonly Middleware[];

- `use`: use(...middleware: Middleware[]): Router;

- `route`: route<const Path extends string>(method: string | readonly string[], path: Path, handler: Handler<PathParams<Path>>, options?: ApiRouteOptions<PathParams<Path>>): Router;

- `get`: get<const Path extends string>(path: Path, handler: Handler<PathParams<Path>>, options?: ApiRouteOptions<PathParams<Path>>): Router;

- `post`: post<const Path extends string>(path: Path, handler: Handler<PathParams<Path>>, options?: ApiRouteOptions<PathParams<Path>>): Router;

- `put`: put<const Path extends string>(path: Path, handler: Handler<PathParams<Path>>, options?: ApiRouteOptions<PathParams<Path>>): Router;

- `patch`: patch<const Path extends string>(path: Path, handler: Handler<PathParams<Path>>, options?: ApiRouteOptions<PathParams<Path>>): Router;

- `delete`: delete<const Path extends string>(path: Path, handler: Handler<PathParams<Path>>, options?: ApiRouteOptions<PathParams<Path>>): Router;

- `options`: options<const Path extends string>(path: Path, handler: Handler<PathParams<Path>>, options?: ApiRouteOptions<PathParams<Path>>): Router;

- `head`: head<const Path extends string>(path: Path, handler: Handler<PathParams<Path>>, options?: ApiRouteOptions<PathParams<Path>>): Router;

- `trace`: trace<const Path extends string>(path: Path, handler: Handler<PathParams<Path>>, options?: ApiRouteOptions<PathParams<Path>>): Router;

- `connect`: connect<const Path extends string>(path: Path, handler: Handler<PathParams<Path>>, options?: ApiRouteOptions<PathParams<Path>>): Router;

- `ws`: ws<const Path extends string>(path: Path, handler: WebSocketHandler<PathParams<Path>>, options?: ApiRouteOptions<PathParams<Path>>): Router;

### `safeRedirect`

```ts
safeRedirect: (fallback: string, options?: SafeRedirectOptions) => (value: unknown) => string
```

Creates a validator that resolves an untrusted redirect target to a safe, same-origin,
relative path — or to `fallback` if the value is unsafe (absolute, protocol-relative,
contains a scheme, control characters, `..` traversal, backslashes, or an unwanted hash).

### `SafeRedirectOptions`

```ts
SafeRedirectOptions: any
```

Options for {@link safeRedirect}.

- `allowHash`: Allow redirect targets that include a URL fragment (`#...`). Defaults to disallowed.

### `ServerApp`

```ts
ServerApp: any
```

A configured server application, as returned by {@link createServerApp }.

- `fetch`: fetch(request: Request, dispatchOptions?: ServerDispatchOptions): Promise<Response>;

### `ServerAppOptions`

```ts
ServerAppOptions: any
```

Options accepted by {@link createServerApp } to configure a server application.

- `router`: router?: Router;

- `routes`: routes?: readonly ApiRoute[];

- `middleware`: middleware?: readonly Middleware[];

- `onError`: onError?: (error: unknown, context: ServerContext) => Response | Promise<Response>;

- `onAccessDenied`: onAccessDenied?: AccessDeniedHandler;

- `auth`: auth?: AuthResolver;

- `fallback`: fallback?: Handler;

- `websocket`: websocket?: WebSocketAdapter;

- `probes`: probes?: ProbeOptions;

- `telemetry`: telemetry?: ServerTelemetry;

- `maxRequestBytes`: maxRequestBytes?: number;

### `ServerContext`

```ts
ServerContext: any
```

The per-request context passed to handlers and middleware, bundling the incoming request,
parsed URL/params/query, auth state, and a family of response-building helper methods
(`json`, `ok`, `notFound`, `problem`, `setCookie`, `upgrade`, etc.).

- `request`: request: Request;

- `url`: url: URL;

- `params`: params: RouteParams;

- `headers`: headers: Headers;

- `query`: query: URLSearchParams;

- `state`: state: RequestState;

- `auth`: auth: AuthContext;

- `signal`: signal: AbortSignal;

- `sse`: sse(options?: Omit<EventStreamOptions, "signal">): EventStream;

- `telemetry`: telemetry?: ServerTelemetry;

- `bind`: bind<T extends object = Record<string, unknown>>(): Promise<T>;

- `json`: json(value: JsonValue, init?: ResponseInit): Response;

- `text`: text(value: string, init?: ResponseInit): Response;

- `redirect`: redirect(location: string, status?: 301 | 302 | 303 | 307 | 308): Response;

- `ok`: ok(value?: JsonValue, init?: ResponseInit): Response;

- `created`: created(value?: JsonValue, init?: ResponseInit): Response;

- `accepted`: accepted(value?: JsonValue, init?: ResponseInit): Response;

- `noContent`: noContent(init?: ResponseInit): Response;

- `badRequest`: badRequest(message?: string, init?: ResponseInit): Response;

- `bad`: bad(message?: string, init?: ResponseInit): Response;

- `unauthorized`: unauthorized(message?: string, init?: ResponseInit): Response;

- `forbidden`: forbidden(message?: string, init?: ResponseInit): Response;

- `notFound`: notFound(message?: string, init?: ResponseInit): Response;

- `conflict`: conflict(message?: string, init?: ResponseInit): Response;

- `unprocessableEntity`: unprocessableEntity(message?: string, init?: ResponseInit): Response;

- `tooManyRequests`: tooManyRequests(message?: string, init?: ResponseInit): Response;

- `methodNotAllowed`: methodNotAllowed(allow?: string | readonly string[], init?: ResponseInit): Response;

- `error`: error(status?: number, message?: string, init?: ResponseInit): Response;

- `internalServerError`: internalServerError(message?: string, init?: ResponseInit): Response;

- `serverError`: serverError(message?: string, init?: ResponseInit): Response;

- `notImplemented`: notImplemented(message?: string, init?: ResponseInit): Response;

- `serviceUnavailable`: serviceUnavailable(message?: string, init?: ResponseInit): Response;

- `problem`: problem(status: number, detail?: string, options?: ProblemOptions): Response;

- `challenge`: challenge(options?: ChallengeOptions): Response;

- `setCookie`: setCookie(response: Response, name: string, value: string, options?: CookieOptions): Response;

- `clearCookie`: clearCookie(response: Response, name: string, options?: CookieOptions): Response;

- `upgrade`: upgrade(handler: WebSocketHandler): Response | Promise<Response>;

### `ServerDispatchOptions`

```ts
ServerDispatchOptions: any
```

Per-request options passed to {@link ServerApp.fetch}.

- `websocket`: websocket?: WebSocketAdapter;

### `serverError`

```ts
serverError: (detail?: string, init?: ResponseInit) => Response
```

Alias for {@link internalServerError}.

### `ServerSentEvent`

```ts
ServerSentEvent: any
```

A single Server-Sent Event; `data` is JSON-serialized unless already a string.

- `data`: data?: unknown;

- `event`: event?: string;

- `id`: id?: string;

- `retry`: retry?: number;

### `ServerTelemetry`

```ts
ServerTelemetry: any
```

Telemetry hooks that a {@link ServerAppOptions.telemetry} implementation provides. Each
`work`-wrapping method should run `work` inside an appropriately named span, propagating its
return value.

- `request`: request<T>(fields: ServerTelemetryFields, work: () => T): T;

- `routeMatch`: routeMatch<T>(fields: ServerTelemetryFields, work: () => T): T;

- `loader`: loader?<T>(fields: ServerTelemetryFields, work: () => T): T;

- `action`: action<T>(fields: ServerTelemetryFields, work: () => T): T;

- `apiOperation`: apiOperation<T>(fields: ServerTelemetryFields, work: () => T): T;

- `queryPrefetch`: queryPrefetch?<T>(fields: ServerTelemetryFields, work: () => T): T;

- `ssrRender`: ssrRender?<T>(fields: ServerTelemetryFields, work: () => T): T;

- `log`: log(level: "debug" | "info" | "warn" | "error", event: ServerTelemetryOperation, fields?: ServerTelemetryFields): void;

- `traceId`: traceId(): string | undefined;

- `extract`: extract?<Carrier>(carrier: Carrier, getter: {
    keys(value: Carrier): string[];
    get(value: Carrier, key: string): string | string[] | undefined;
  }): unknown;

- `withContext`: withContext?<T>(context: unknown, work: () => T): T;

### `ServerTelemetryFields`

```ts
ServerTelemetryFields: any
```

Contextual fields attached to a telemetry span or log entry.

- `requestId`: requestId?: string;

- `traceId`: traceId?: string;

- `route`: route?: string;

- `action`: action?: string;

- `operation`: operation?: string;

- `status`: status?: number;

- `durationMs`: durationMs?: number;

### `ServerTelemetryOperation`

```ts
ServerTelemetryOperation: "askr.request" | "askr.route.match" | "askr.loader" | "askr.action" | "askr.api.operation" | "askr.query.prefetch" | "askr.ssr.render" | "askr.vite.document"
```

Identifies the kind of operation a {@link ServerTelemetry} call is instrumenting.

### `serviceUnavailable`

```ts
serviceUnavailable: (detail?: string, init?: ResponseInit) => Response
```

Builds a `503 Service Unavailable` Problem Details response.

### `setCookie`

```ts
setCookie: (response: Response, name: string, value: string, options?: CookieOptions) => Response
```

Returns a clone of `response` with an additional `Set-Cookie` header appended, serialized
from `name`, `value`, and `options`.

### `text`

```ts
text: (value: string, init?: ResponseInit) => Response
```

Builds a plain-text response, setting the `text/plain; charset=utf-8` content type.

### `TokenIssuer`

```ts
TokenIssuer: any
```

Issues auth tokens for a principal, used by {@link registerAuthRoutes} to mint session tokens.

- `issue`: issue(principal: Omit<P, "id"> & {
    subject: string;
  }): Promise<string>;

### `tooManyRequests`

```ts
tooManyRequests: (detail?: string, init?: ResponseInit) => Response
```

Builds a `429 Too Many Requests` Problem Details response.

### `unauthorized`

```ts
unauthorized: (detail?: string, init?: ResponseInit) => Response
```

Builds a `401 Unauthorized` Problem Details response.

### `unprocessableEntity`

```ts
unprocessableEntity: (detail?: string, init?: ResponseInit) => Response
```

Builds a `422 Unprocessable Entity` Problem Details response.

### `WebSocketAdapter`

```ts
WebSocketAdapter: any
```

Adapter that performs the transport-specific work of upgrading a request to a WebSocket.

- `upgrade`: upgrade(request: Request, handler: WebSocketHandler, context: ServerContext): Response | Promise<Response>;

### `WebSocketCloseEvent`

```ts
WebSocketCloseEvent: any
```

Details of a WebSocket close event, mirroring the DOM `CloseEvent` fields used here.

- `code`: readonly code: number;

- `reason`: readonly reason: string;

- `wasClean`: readonly wasClean: boolean;

### `WebSocketHandler`

```ts
WebSocketHandler: {
  bivarianceHack(socket: WebSocketLike, context: ServerContext<RouteParams>): void | Promise<void>;
}["bivarianceHack"]
```

Handler invoked with a live {@link WebSocketLike} once a connection has been upgraded.

### `WebSocketLike`

```ts
WebSocketLike: any
```

Transport-neutral interface for an upgraded WebSocket connection.

- `send`: send(data: string | ArrayBufferLike | ArrayBufferView): void;

- `close`: close(code?: number, reason?: string): void;

- `onMessage`: onMessage(listener: (data: string | Uint8Array) => void): () => void;

- `onClose`: onClose(listener: (event: WebSocketCloseEvent) => void): () => void;

- `onError`: onError(listener: (error: unknown) => void): () => void;

## Documentation navigation

[Previous](https://askrjs.com/docs/reference/api/schema/root/index.md) | [Next](https://askrjs.com/docs/reference/api/server/router/index.md)
