--- title: "Request lifecycle" description: "Follow a Beignet request through route matching, parsing, hooks, context, handlers, validation, errors, and response ownership." url: "https://www.beignetjs.com/request-lifecycle" markdown_url: "https://www.beignetjs.com/markdown/request-lifecycle.md" framework_version: "0.0.65" documentation_scope: "current-checkout" source_revision: "e5b4771b262efbdd036e3a40a514c08d1508316c" source_modified: true --- # Request lifecycle A Beignet request moves through a predictable pipeline before your application code runs and before a response is sent. Read this page when you need to know what the framework guarantees around a request — matching, validation, correlation, and who owns each kind of response. For a matched route, the pipeline is: ```txt HTTP request -> adapter request normalization -> route matching -> request correlation (request ID + trace context) -> onRequest hooks -> request parsing -> contract request validation -> context creation -> route hooks -> beforeHandle hooks -> route handler or use case -> beforeSend hooks (correlation response headers) -> route-owned response validation -> adapter response serialization -> afterSend hooks (instrumentation events) ``` This pipeline keeps business responses strict without forcing every route to declare infrastructure responses such as malformed JSON, auth failures, rate limits, unmatched routes, or unexpected failures. ## Route matching Beignet apps register routes centrally in `server/index.ts` with `defineRoutes`. Next.js apps expose them through `createApiRoute(getServer)` in a catch-all `app/api/[[...path]]/route.ts`; standard Fetch runtimes mount the `server.fetch` handler returned by `createFetchServer(...)`. Both adapters dispatch the incoming request through the same registered contract and handler pipeline. Routes are matched by HTTP method and path. Static segments are more specific than dynamic segments, so `/posts/new` wins over `/posts/:slug` regardless of registration order. Dynamic parameter names do not affect matching — registering both `/items/:id` and `/items/:slug` for the same method is rejected at startup as ambiguous, along with the other [registration-time guarantees](https://www.beignetjs.com/markdown/server.md#registration-time-guarantees). Non-HEAD requests to fully static paths use a direct method-and-path lookup when the request matches their encoded spelling. Other requests narrow candidate routes by path depth and the literal prefix before the first parameter, then use the existing pattern matcher. This also applies to HEAD and 404/405 handling. Matching still preserves static-before-dynamic precedence and equivalent lowercase percent escapes; it never decodes a path before selecting candidates. Routes sharing a prefix, including routes that start with a parameter, can still require a scan. Indexes retain registered routes, not request URLs, and update after `server.route(...)` registration. Validation, context creation, hooks, and instrumentation continue through the same request pipeline. If the path matches one or more registered routes but the method does not, Beignet returns a framework-owned `405` response with `code: "METHOD_NOT_ALLOWED"` and an `Allow` header listing the registered methods for that path. A `GET` route also serves `HEAD` when the path has no explicit `HEAD` route. Explicit `HEAD` routes take precedence, `Allow` includes the implicit method, and every HEAD response is bodyless while preserving its status and headers. CORS preflight `onRequest` hooks still short-circuit `OPTIONS` requests before a `405` is produced. If no route matches the path at all, Beignet returns a framework-owned `404` error response. Both central `server.api` dispatch and focused `server.route(contract).handle(...)` adapters run these fallback responses through `onRequest`, `beforeSend`, and `afterSend`, with request correlation, tracing, instrumentation, CORS, and security headers. They skip request parsing, context creation, route hooks, and `beforeHandle`. A failing session or database lookup in your context factory therefore cannot turn a routing miss into a 500. Response hooks receive `ctx: undefined` for these responses. Guard access to application context; use `req`, `requestInfo`, and the response's headers and status for context-independent behavior. The skipped stages report `0` in request timings. A matched route that returns or throws an application 404 runs its normal context and authorization pipeline. ## Request validation The runtime parses path params, query params, headers, and JSON body data from the request. It validates each declared schema before your handler runs. JSON parsing recognizes `application/json` and `application/*+json`, matches media types case-insensitively, and ignores parameters such as `charset=utf-8`. Invalid request data never reaches the handler. It becomes a framework-owned error response with a standard error envelope. When a body is a valid JSON object or array but omits `Content-Type`, Beignet still treats it as text according to HTTP semantics. If body validation then fails, `details.hint` explains that `Content-Type: application/json` is needed; explicit text content types do not receive that suggestion. ## Request instrumentation The server owns request correlation. You can rely on these outcomes without writing any hooks: - Incoming request IDs must contain 1–128 ASCII letters, digits, `.`, `_`, `:`, or `-`. Missing or invalid values receive a generated ID before context creation. This also applies to a custom `requestIdHeader`. IDs provide correlation and do not establish caller identity. - Every request gets a request ID and W3C trace context — taken from valid incoming `x-request-id` and `traceparent` headers when present, generated otherwise — available to context factories as `requestId` and `trace`. - By default the server writes `x-request-id` and `traceparent` response headers, including on streamed responses. - `request` and `error` events are recorded to the resolved provider instrumentation port (see [Writing a provider](https://www.beignetjs.com/markdown/writing-a-provider.md)) after responses are sent; without an installed sink, headers are still written and events are a no-op. - Correlation is ambient for the request's duration, so instrumentation sinks can correlate events recorded anywhere in the request. - When `ports.tracing` is installed, the request runs inside an active `beignet.request ` span. Nested use cases and provider SDK spans inherit that OpenTelemetry context across asynchronous work. Configure it with the `instrumentation` option on `createServer(...)`: ```typescript const server = await createNextServer({ // ... instrumentation: { requestIdHeader: "x-request-id", // or false traceContextHeader: "traceparent", // or false ignorePaths: ["/api/devtools"], redact: (event) => event, shouldCapture: ({ response }) => response.status !== 404, }, }); ``` Pass `instrumentation: false` to disable headers and event recording. Context factories still receive `requestId` and `trace` arguments, and ambient audit wrappers still inherit request, actor, tenant, and trace correlation. Context values win over server-computed correlation: when a factory sets its own `requestId`, headers and recorded events use it. `ignorePaths` suppresses instrumentation events for matching routes without removing their ambient correlation. Install `@beignet/provider-tracing-opentelemetry` to turn correlation into production spans and metrics. The app still owns SDK registration, sampling, export, and serverless flush behavior. See [OpenTelemetry](https://www.beignetjs.com/markdown/observability.md). ## Per-stage timings Every request records a per-stage timing breakdown alongside its total duration. `afterSend` hooks receive it as `stages`, and the recorded `request` event carries the same object, which the [devtools waterfall](https://www.beignetjs.com/markdown/devtools.md) renders as sub-bars under the request span: | Stage | Measures | | ---------------- | -------------------------------------------------------------------------------- | | `onRequestMs` | `onRequest` hooks, including early rate limits and CORS preflight | | `parseMs` | Query/path/header/body parsing and contract validation | | `contextMs` | The `context.request` factory, including gate attachment | | `beforeHandleMs` | Route hooks plus `beforeHandle` hooks (auth resolution, user-scoped rate limits) | | `handlerMs` | The route handler or bound use case | | `sendMs` | `beforeSend` hooks, response validation, and finalizers | Stages that did not run report `0`, and the stages do not sum exactly to `durationMs` — routing and framework bookkeeping live in the gaps. ## Context latency budgets `contextMs` is the number to watch in serverless deployments with a remote database. The `context.request` factory runs for matched routes after `onRequest` and request validation succeed. Each sequential `await` inside it — a session lookup, then a membership query — adds a full database round-trip before the handler. Two sequential 120ms remote queries put a \~240ms floor under those requests before business logic starts. Router-generated 404/405 responses skip this work. Budget context creation like the hot path it is: - Run independent lookups concurrently with `Promise.all` instead of sequential awaits, and resolve dependent data (a role for the resolved tenant) inside the use cases that need it when most routes do not. - Cache what the auth provider lets you cache — for example Better Auth's `cookieCache` avoids a session query per request. - Wrap repository reads in [`createMemo`](https://www.beignetjs.com/markdown/request-lifecycle.md#request-scoped-memoization) so a lookup the context factory already resolved is not paid again by policies and use cases in the same request. - Keep the factory to identity and correlation. Loading feature data in context makes every route pay for the heaviest route's needs. - Watch the waterfall in development: a wide `context` bar on every request is this problem, and it shows up long before production traffic does. ## Request-scoped memoization `createMemo` from `@beignet/core/memo` deduplicates a lookup for the lifetime of one request: the first call runs, and every later call with the same arguments — from a policy, a use case, an event handler — returns the same value, including the same in-flight promise, so concurrent calls share one query. The cache dies with the request, so memoized reads can never serve data staler than the request that fetched them: no TTL, no invalidation policy, no cross-request state. Wrap reads where the adapter is wired, in infra, so use cases and policies never know caching exists: ```typescript // infra/issues-repository.ts import { createMemo } from "@beignet/core/memo"; const repository = createDrizzleIssuesRepository(db); export const issues = { ...repository, findById: createMemo(repository.findById, { name: "issues.findById" }), update: async (id: string, patch: IssuePatch) => { const updated = await repository.update(id, patch); // A write makes the memoized read stale within this same request. issues.findById.invalidate(id); return updated; }, }; ``` Memoize reads, not mutations, and pair every mutation that affects a memoized read with `invalidate(...)` as above. Default cache keys use a structural, type-tagged encoding of the arguments (`"1"` and `1` never collide, object key order is irrelevant); arguments that cannot be encoded deterministically — class instances, functions, circular values — throw a `MemoKeyError` that names the memo, and a `key` option takes over: ```typescript createMemo(repository.search, { name: "issues.search", key: (query) => query.normalized, }); ``` The server enters a memo scope around every HTTP request (contract routes and raw routes) and around `server.runServiceContext(...)` executions, and `createTestApp` requests each get their own scope. `createServiceContext(...)` has no call boundary that could end a scope, so memoized functions call straight through there — as they do in plain scripts, where `runMemoScope` from `@beignet/core/memo` creates a scope explicitly. When devtools is installed, every memoized call records a `memo.hit` or `memo.miss` event (with fill duration) under the request, so duplicate lookups are visible in the waterfall before and after you wrap them. For caching that must survive across requests — the remote-database session and role floor above — reach for the explicit tier instead: the auth provider's cookie cache for sessions, and `ports.cache.remember` with keys that change when the data changes (a per-tenant version segment, for example) for everything else. Cross-request caching trades staleness for latency and needs an invalidation story; request-scoped memoization never does, which is why it is the tier the framework applies automatically. ## Context and hooks The server's `context.request` factory builds the per-request context used by handlers, hooks, and use cases from the framework-neutral request, final ports, the matched contract, and the server-resolved `requestId` and `trace` values. See [Server](https://www.beignetjs.com/markdown/server.md#context) for the context blueprint and service contexts. When the context blueprint declares a `gate`, the server attaches `ctx.gate` itself and re-attaches it after hooks enrich the context, so authorization always evaluates the current identity. Hooks run around the handler for application-level behavior: authentication at the HTTP boundary, CORS, logging and tracing, rate limiting, response shaping, and error mapping. Hooks can short-circuit the request; short-circuit responses are framework-owned unless the hook returns a native `Response`. See [Hooks](https://www.beignetjs.com/markdown/hooks.md) for the lifecycle order and hook kinds. ## Route execution After validation, the route runs. Binder routes (`{ contract, useCase }`) map the validated request parts to the use case input, run the use case, and return its output with the contract's declared success status: ```typescript { contract: getProject, useCase: getProjectUseCase, } ``` When the route shares schemas by reference with its use case, Beignet skips the redundant second validation pass. See [Server](https://www.beignetjs.com/markdown/server.md#route-registration) for the binder's input mapping and one-schema-one-parse rules. Full `handle` routes receive the validated parts directly and own the response: ```typescript { contract: getProject, handle: async ({ req, ctx, path, query, headers, body }) => ({ status: 200, body: await getProjectUseCase.run({ ctx, input: { id: path.id } }), }), } ``` ## Response ownership Beignet separates responses into three groups: | Owner | Source | Validation | | --------------- | ---------------------------------------------------------------------------------------- | -------------------------------------- | | Route-owned | Bound use case output, handler `{ status, body }`, or route-owned `AppError` | Parsed through `contract.responses` | | Framework-owned | Parsing, validation, hooks, unmatched routes, global error handling, contract violations | Uses Beignet's standard error envelope | | Transport-owned | Native `Response` returned by handler or hook | Bypasses JSON response validation | Route-owned responses are business outcomes: responses returned by the handler, and `AppError` instances thrown by the handler or bound use case. When the route declares response schemas, an undeclared status or a non-matching body becomes a framework-owned 500 contract-violation response; otherwise Beignet sends the response schema's parsed output. This makes schema stripping and transforms part of the wire response, including transforms on catalog error details. An empty `contract.responses` applies no response validation or transformation. The `validateResponses` server option and its production posture live in [Server](https://www.beignetjs.com/markdown/server.md#response-validation). Framework-owned responses skip route response validation and use Beignet's standard error envelope when applicable: - Request parsing and request validation errors - Unmatched route 404s and method-mismatch 405s - Hook short-circuit responses from `onRequest` or `beforeHandle` - `mapUnhandledError` responses - Internal contract-violation 500s Framework-owned Beignet error envelopes include `x-beignet-error-owner: framework` so generated clients can distinguish framework errors from route-owned error responses that share the same status code. Transport-owned responses are native `Response` objects returned from handlers or hooks. They bypass JSON response validation, and `beforeSend` sees a headers-only view where only header changes apply; `afterSend` still observes their status and headers. Plain Beignet responses can intentionally send text, or binary data by declaring an explicit non-JSON `Content-Type` and returning a Web `BodyInit` value through `@beignet/web` or `@beignet/next`. Explicit `ReadableStream` bodies remain streams for every media type, including JSON. Use a native response for redirects, multipart boundary generation, Server-Sent Events, or other transport-specific behavior. HTTP statuses 204, 205, and 304 are always required to be bodyless. Beignet checks that invariant inside the server pipeline even when response schemas are absent or `validateResponses` is disabled, so violations still pass through error mapping, finalizers, lifecycle headers, and instrumentation. If a response-schema validator itself throws unexpectedly, Beignet maps that failure through the same pipeline before running response finalizers. Hooks therefore receive the mapped failure; the idempotency hook can release its reservation instead of leaving the key in progress until its timeout. This keeps the contract strict for business responses while letting infrastructure concerns such as auth, CORS, rate limits, malformed requests, and unexpected failures stay outside each route's response union. ## Client behavior Typed clients use the same contracts. A non-2xx route-owned response is parsed against the declared error response schema. Framework-owned errors use Beignet's standard `{ code, message, details?, requestId? }` envelope when the response includes Beignet's ownership header. Use `call()` when failures should throw `ContractError`. Use `safeCall()` when explicit result branching is clearer. See [Client](https://www.beignetjs.com/markdown/client.md#error-handling) for narrowing and handling patterns.