Skip to main content

HttpContext

HttpContext is the execution context passed to every HTTP operation handler. It provides decoded and validated access to all parts of the incoming request — path parameters, query parameters, headers, cookies, and the request body — and exposes the raw Node.js request/response objects for cases that require lower-level control.

Package: @opra/http


Properties

PropertyTypeDescription
requestHttpRequestThe incoming HTTP request. → See HttpRequest
responseHttpResponseThe outgoing HTTP response. → See HttpResponse
pathParamsRecord<string, any>Decoded path parameters, keyed by the name declared in .PathParam().
queryParamsRecord<string, any>Decoded query string parameters, keyed by the name declared in .QueryParam().
headersRecord<string, any>Decoded request headers, keyed by the name declared in .Header().
cookiesRecord<string, any>Decoded cookies, keyed by the name declared in .Cookie().
errorsError[]Accumulated errors during request processing. The adapter checks this after the handler returns.
mediaTypeHttpMediaType | undefinedThe matched request content type definition, derived from the .RequestContent() declaration.
isMultipartbooleantrue when the request Content-Type is multipart/*.
bundleHttpBundle | undefinedThe HttpBundle this context belongs to, if the request arrived as part of a multipart/mixed batch. undefined for standalone requests.
note

pathParams, queryParams, headers, and cookies only contain parameters explicitly declared on the controller or operation. Use ctx.request to access undeclared values from the raw request.


Methods

getBody<T>()

getBody<T>(args?: { toFile: boolean | string }): Promise<T>

Reads, parses, and validates the request body. The body is cached — calling getBody() multiple times returns the same decoded value.

Supported content types out of the box: application/json, application/yaml, application/toml, text/plain, and binary. The actual decode is driven by the type declared in .RequestContent().

ParameterTypeDescription
args.toFileboolean | stringSave the raw body to a temp file instead of buffering in memory. Pass true for an auto-named file or a string for a specific path.
// JSON body — decoded against the declared RequestContent type
const body = await ctx.getBody<Customer>();

// Save a large binary upload to a temp file
const file = await ctx.getBody<LocalFile>({ toFile: true });

Throws BadRequestError if parsing or validation fails.


getMultipartReader()

getMultipartReader(): Promise<MultipartReader>

Returns a MultipartReader for streaming a multipart/form-data request. The same instance is returned on repeated calls.

if (ctx.isMultipart) {
const reader = await ctx.getMultipartReader();
const parts = await reader.getAll();
}

Throws InternalServerError if the request is not multipart.
Throws NotAcceptableError if the operation does not declare .MultipartContent().


Events

HttpContext extends AsyncEventEmitter and emits the following typed events during its lifecycle. Listen on the context instance, or observe all contexts via the adapter's context-* events.

EventPayloadEmitted when
'before-execute'ctx: HttpContextImmediately before the operation handler is called.
'after-execute'responseValue: any, ctx: HttpContextAfter the operation handler returns successfully.
'error'error: Error, ctx: HttpContextAn unhandled error occurs during execution.
'finish'ctx: HttpContextThe context lifecycle is complete. Always fires, whether successful or not.
adapter.on('create-context', ctx => {
ctx.on('before-execute', ctx => {
console.log(`${ctx.request.method} ${ctx.request.url}`);
});
ctx.on('finish', ctx => {
console.log(`${ctx.response.statusCode} success=${ctx.success}`);
});
});
tip

For request-scoped observability (logging, tracing), prefer the adapter-level context-before-execute / context-after-execute / context-finish events over attaching listeners to individual context instances. See HttpAdapter.Events.


info

ctx.request is an HttpRequest — a Node.js IncomingMessage extended with Express-compatible helpers for headers, content negotiation, and body reading.

ctx.response is an HttpResponse — a Node.js ServerResponse extended with Express-compatible helpers for cookies, redirects, and response status. In most OPRA handlers you return a value instead of writing to the response directly.