elysiajs/elysia

Ergonomic Framework for Humans

18,043 stars TypeScript 10 components

Type-safe HTTP server framework with automatic request/response validation and adapter-based deployment

Requests flow through adapter-specific parsing into a shared Context object, get validated against schemas, pass through lifecycle hooks (beforeHandle, transform, etc.), execute the user handler, and format responses back through the adapter. The Sucrose analyzer optimizes this pipeline at compile time by detecting which context properties each handler uses.

Under the hood, the system uses 3 feedback loops, 4 data pools, 4 control points to manage its runtime behavior.

A 10-component backend api. 238 files analyzed. Data flows through 5 distinct pipeline stages.

How Data Flows Through the System

Requests flow through adapter-specific parsing into a shared Context object, get validated against schemas, pass through lifecycle hooks (beforeHandle, transform, etc.), execute the user handler, and format responses back through the adapter. The Sucrose analyzer optimizes this pipeline at compile time by detecting which context properties each handler uses.

  1. Adapter Request Parsing — Runtime adapters (BunAdapter, WebStandardAdapter) parse incoming HTTP requests into standardized Context objects, extracting headers, body, query parameters, and cookies using adapter-specific APIs [Raw HTTP Request → Context]
  2. Schema Validation — getSchemaValidator creates ElysiaTypeCheck instances from route schemas, then validates the request body, query, headers, and cookies against their definitions using TypeBox or StandardSchema [Context → Validated Context]
  3. Lifecycle Hook Execution — composeHandler executes the lifecycle chain: request hooks modify context, parse hooks handle custom body parsing, transform hooks mutate data, beforeHandle hooks can short-circuit, then the main handler executes [Validated Context → Handler Response]
  4. Response Processing — afterHandle hooks can modify the response, mapResponse hooks transform the final output, and afterResponse hooks run after sending (for cleanup), while error hooks catch exceptions at any stage [Handler Response → Final Response]
  5. Adapter Response Formatting — Adapters format the final response using mapResponse, mapEarlyResponse, or mapCompactResponse functions, setting proper headers, status codes, and body content for the target runtime [Final Response → Runtime HTTP Response]

Data Models

The data structures that flow between stages — the contracts that hold the system together.

Context src/context.ts
Generic type with body: RouteSchema['body'], query: Record<string, string | undefined>, params: ResolvePath<Path>, headers: Record<string, string | undefined>, cookie: Record<string, Cookie>, server: Server | null, set: { headers, status, redirect, cookie }
Created from incoming request, passed through all lifecycle hooks, and used to generate the final response
RouteSchema src/types.ts
Object with optional body, query, params, headers, cookie, and response properties that define the expected shape of a route's input and output
Defined at route registration, compiled into validators, and used for runtime validation and TypeScript inference
ElysiaTypeCheck src/schema.ts
Validator object with schema: T, Check(value): boolean | { value } | { issues }, parse(value): T, safeParse(value): { success, data, error }, plus metadata flags for hasDefault, isOptional, hasTransform
Compiled from schema definitions, used to validate and transform request/response data at runtime
Handler src/types.ts
Function type (context: Context) => Response | Promise<Response> with generic type parameters for route schema and singleton types
Defined by user, wrapped with lifecycle hooks, and executed during request processing
LifeCycleStore src/types.ts
Object with optional arrays: request, parse, transform, beforeHandle, afterHandle, mapResponse, afterResponse, error - each containing handler functions
Built up during app configuration, compiled into the final request handler chain

Hidden Assumptions

Things this code relies on but never validates. These are the things that cause silent failures when the system changes.

critical Domain unguarded

FNV-1a hash constants (FNV_OFFSET_BASIS=2166136261, FNV_PRIME=16777619) are correct mathematical values for 32-bit FNV-1a hashing but code assumes strings will never collide in practical usage

If this fails: Hash collisions in cookie signing could allow an attacker to forge cookies with the same hash signature, bypassing authentication or authorization checks

src/cookies.ts:hashString
critical Environment weakly guarded

Environment detection assumes either Bun.env or process.env exists, but fallback to undefined means isProduction defaults to false when neither is available

If this fails: In unknown runtime environments, production optimizations are disabled and verbose error messages are shown, potentially leaking sensitive information in production deployments

src/error.ts:env
critical Shape weakly guarded

FormData entries with string values starting with '{' or '[' (charCodeAt 123 or 91) are valid JSON objects that can be safely parsed, but no validation that parsed result is actually an object

If this fails: Malicious form data like '{malicious: 1, __proto__: {isAdmin: true}}' could inject properties into the request body object, potentially leading to prototype pollution attacks

src/adapter/web-standard/index.ts:formData parser
warning Scale unguarded

Default garbage collection time of 4 minutes 55 seconds (295000ms) is appropriate for all applications regardless of their request volume, memory constraints, or handler complexity

If this fails: High-traffic applications may run out of memory before GC kicks in, while low-traffic applications may hold unnecessary cache data too long, leading to memory pressure or OOM crashes

src/sucrose.ts:gcTime
warning Ordering unguarded

Optional route parameters (ending with '?') can be processed by recursively removing them in any order, but assumes the route pattern follows standard Express-like conventions

If this fails: Non-standard route patterns could generate incorrect route variations, causing requests to match wrong handlers or miss valid routes entirely

src/adapter/bun/index.ts:getPossibleParams
warning Contract weakly guarded

TypeBox schemas return boolean while StandardSchema returns either {value} or {issues} objects, but calling code must know which provider is being used to handle return types correctly

If this fails: Type checking logic that assumes boolean returns will crash when StandardSchema validators return objects, or vice versa, leading to runtime type errors in validation pipelines

src/schema.ts:ElysiaTypeCheck.Check
warning Resource unguarded

FormData.getAll() for each key and JSON.parse() attempts on string values will complete within reasonable time and memory limits regardless of form data size or nesting depth

If this fails: Large form uploads or deeply nested JSON in form fields could consume excessive CPU/memory during parsing, potentially causing DoS or server crashes on resource-constrained environments

src/adapter/web-standard/index.ts:formData parsing
warning Domain weakly guarded

Only '__proto__', 'constructor', and 'prototype' are dangerous property names, and array notation regex /^(.+)\[(\d+)\]$/ catches all dangerous array-like keys

If this fails: Other prototype pollution vectors like 'hasOwnProperty[constructor][prototype]' or '__defineGetter__' could bypass the protection, allowing attackers to modify object prototypes through form data

src/adapter/web-standard/index.ts:dangerousKeys
info Temporal unguarded

Cookie modifications during request processing are accumulated and all changes can be serialized atomically at response time, but no handling of concurrent cookie updates

If this fails: In async handlers that modify cookies concurrently, some cookie changes could be lost or overwritten, leading to inconsistent authentication state or lost user preferences

src/cookies.ts:Cookie storage
info Environment weakly guarded

Cloudflare Worker environment is detected correctly and listen() method should never be called, but only shows console warning instead of throwing error

If this fails: Applications mistakenly calling listen() in Cloudflare Worker environments fail silently with only a console warning, making deployment issues harder to debug

src/adapter/cloudflare-worker/index.ts:listen

System Behavior

How the system operates at runtime — where data accumulates, what loops, what waits, and what controls what.

Data Pools

Route Registry (registry)
Stores compiled route handlers indexed by HTTP method and path pattern, with metadata for type checking and optimization
Schema Cache (cache)
Caches compiled TypeBox validators and StandardSchema instances to avoid recompilation of identical schemas
Cookie Store (state-store)
Manages signed cookie values with secrets, tracks cookie modifications during request processing
Sucrose Analysis Cache (cache)
Caches static analysis results of handler functions to determine which context properties are accessed

Feedback Loops

Delays

Control Points

Technology Stack

TypeScript (runtime)
Provides compile-time type safety, complex type inference for request/response schemas, and enables static analysis optimizations
TypeBox (library)
JSON Schema-based validation library that generates both TypeScript types and runtime validators from schema definitions
Bun (runtime)
Primary target runtime providing native HTTP server, WebSocket support, and optimized JavaScript execution for the BunAdapter
Web Standards APIs (framework)
Request/Response interfaces that enable cross-runtime compatibility through the WebStandardAdapter
cookie (library)
Cookie parsing and serialization library used by the cookie management system for HTTP cookie handling
memoirist (library)
Efficient route matching library that handles path parameters, wildcards, and route prioritization

Key Components

Explore the interactive analysis

See the full architecture map, data flow, and code patterns visualization.

Analyze on CodeSea

Related Backend Api Repositories

Frequently Asked Questions

What is elysia used for?

Type-safe HTTP server framework with automatic request/response validation and adapter-based deployment elysiajs/elysia is a 10-component backend api written in TypeScript. Data flows through 5 distinct pipeline stages. The codebase contains 238 files.

How is elysia architected?

elysia is organized into 4 architecture layers: Framework Core, Adapter Layer, Schema System, Context & Lifecycle. Data flows through 5 distinct pipeline stages. This layered structure keeps concerns separated and modules independent.

How does data flow through elysia?

Data moves through 5 stages: Adapter Request Parsing → Schema Validation → Lifecycle Hook Execution → Response Processing → Adapter Response Formatting. Requests flow through adapter-specific parsing into a shared Context object, get validated against schemas, pass through lifecycle hooks (beforeHandle, transform, etc.), execute the user handler, and format responses back through the adapter. The Sucrose analyzer optimizes this pipeline at compile time by detecting which context properties each handler uses. This pipeline design reflects a complex multi-stage processing system.

What technologies does elysia use?

The core stack includes TypeScript (Provides compile-time type safety, complex type inference for request/response schemas, and enables static analysis optimizations), TypeBox (JSON Schema-based validation library that generates both TypeScript types and runtime validators from schema definitions), Bun (Primary target runtime providing native HTTP server, WebSocket support, and optimized JavaScript execution for the BunAdapter), Web Standards APIs (Request/Response interfaces that enable cross-runtime compatibility through the WebStandardAdapter), cookie (Cookie parsing and serialization library used by the cookie management system for HTTP cookie handling), memoirist (Efficient route matching library that handles path parameters, wildcards, and route prioritization). A focused set of dependencies that keeps the build manageable.

What system dynamics does elysia have?

elysia exhibits 4 data pools (Route Registry, Schema Cache), 3 feedback loops, 4 control points, 3 delays. The feedback loops handle recursive and recursive. These runtime behaviors shape how the system responds to load, failures, and configuration changes.

What design patterns does elysia use?

5 design patterns detected: Adapter Pattern, Chain of Responsibility, Compile-time Optimization, Type-level Programming, Plugin Architecture.

Analyzed on April 20, 2026 by CodeSea. Written by .