The Context(s)
During the request lifecycle, CrumbJS builds different contexts through the Processor
.
Each context extends the core utilities from RootContext
and is used in a specific stage of the pipeline.
RootContext
The base context available in all stages.
Provides request/response accessors, mutators, and utility helpers.
Main features include:
- Access to the original
Request
,URL
, and clientip
. - Request parsing utilities (
bearer()
,basicCredentials()
). rawBody
with auto-parsed values (JSON, form-data, urlencoded, etc.).- Response controls (
setHeader
,setStatus
,setCookie
, etc.). - A per-request key–value store (
get
/set
) to pass data between middlewares and handlers.
export type RootContext = {
/** start time context resolution: performance.now() */
start: DOMHighResTimeStamp;
/** The original Fetch API Request object */
request: Request;
/** The bun server instance */
server: Bun.Server;
/** extracted request Origin */
origin: string;
/**
* parse bearer authorization returning only the token string
* @throws {BadRequest} on inexistent or short)
*/
bearer: () => string;
/**
* parse the basic authorization returning user and password object
* @throws {BadRequest} on inexistent or invalid)
*/
basicCredentials: () => { user: string; password: string };
/** extracted request client ip address */
ip: string;
/** request URL instance */
url: URL;
/**
* rawBody, is the unvalidated request body parsed into a plain object.
*
* Supported auto-parseables Content-Types:
* - `application/json`
* - `application/x-www-form-urlencoded`
* - `multipart/form-data`
*
* For unsupported types, the body is parsed as text and returned as: `{ content: string }`.
*
* Note: No schema validation is applied to this object and is available and writable in middlewares
*/
rawBody: Record<string, any>;
/**
* Sets a response header.
* @param key - Header name (case-insensitive)
* @param value - Header value
*/
setHeader: (key: string, value: string) => void;
/**
* Removes a response header by name.
* @param key - Header name to delete
*/
deleteHeader: (key: string) => void;
/**
* Gets the current response headers
*/
getResponseHeaders: () => Headers;
/**
* Gets the current response status
*/
getResponseStatus: () => number;
/**
* Sets the HTTP status code and optional status text for the response.
* @param code - HTTP status code (e.g., 200, 404)
* @param text - Optional status message (e.g., "OK", "Not Found")
*/
setStatus: (code: number, text?: string) => void;
/**
* Adds or updates a cookie in the map.
*
* @param name - The name of the cookie
* @param value - The value of the cookie
* @param options - Optional cookie attributes
*/
setCookie: (name: string, value: string, options?: CookieInit) => void;
/**
* Gets the value of a cookie with the specified name.
*
* @param name - The name of the cookie to retrieve
* @returns The cookie value as a string, or null if the cookie doesn't exist
*/
getCookie: (name: string) => string | null;
/**
* Removes a cookie from the map.
*
* @param name - The name of the cookie to delete
*/
deleteCookie: (name: string) => void;
/**
* RequestStores a value in the per-request context.
* Useful for passing data between middlewares and handlers.
* @param key - Unique key
* @param value - Any value to store
*/
set: (key: string, value: any) => void;
/**
* Retrieves a stored value from the per-request context.
* @param key - Key to retrieve
* @returns The stored value
* @throws {InternalServerError} if the key not exists
*/
get: <T = any>(key: string) => T;
};
MiddlewareContext
Created at the start of the Chain of Responsibility. All middlewares run using this context.
Extends RootContext. Adds a next callback to continue execution in the chain.
rawBody is filled but still unvalidated.
export type MiddlewareContext = RootContext & { next: Next };
Context
The most common and primary context used in route handlers.
Extends RootContext. Exposes validated body, query, params, and headers. Validation is powered by Zod schemas; if no schema is provided, the field defaults to any.
export type Context<
PATH extends string = any,
BODY extends ZodObject | undefined = any,
QUERY extends ZodObject | undefined = any,
HEADERS extends ZodObject | undefined = any
> = RootContext & {
body: InferOrAny<BODY>;
query: InferOrAny<QUERY>;
params: ExtractPathParams<PATH>;
headers: InferOrAny<HEADERS>;
};
ErrorContext
Instantiated when an error occurs during request handling. Extends RootContext. Adds the exception object, which is part of CrumbJS’s centralized error system. Used in api errorHandler
export type ErrorContext = RootContext & { exception: Exception };