elysiajs/elysia
Ergonomic Framework for Humans
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.
- 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]
- 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]
- 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]
- 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]
- 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.
src/context.tsGeneric 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
src/types.tsObject 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
src/schema.tsValidator 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
src/types.tsFunction 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
src/types.tsObject 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.
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
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
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
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
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
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
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
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
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
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
Stores compiled route handlers indexed by HTTP method and path pattern, with metadata for type checking and optimization
Caches compiled TypeBox validators and StandardSchema instances to avoid recompilation of identical schemas
Manages signed cookie values with secrets, tracks cookie modifications during request processing
Caches static analysis results of handler functions to determine which context properties are accessed
Feedback Loops
- Handler Compilation Loop (recursive, balancing) — Trigger: Route registration or schema changes. Action: composeHandler analyzes dependencies, generates optimized code, and recompiles the handler chain. Exit: All dependencies resolved and handler compiled.
- Plugin Dependency Resolution (recursive, balancing) — Trigger: Plugin registration with dependencies. Action: Elysia resolves plugin dependencies recursively, loading required plugins and their schemas. Exit: All plugin dependencies satisfied.
- Error Handler Chain (retry, balancing) — Trigger: Exception thrown during request processing. Action: Error bubbles up through lifecycle hooks, each error handler can transform or resolve the error. Exit: Error handler returns response or error reaches top level.
Delays
- Sucrose Analysis Delay (compilation, ~Based on handler complexity) — First request to new routes may have higher latency while handler functions are analyzed and compiled
- Schema Compilation Delay (compilation, ~Based on schema complexity) — TypeBox schema compilation happens on first use, subsequent requests use cached validators
- Plugin Loading Delay (async-processing, ~Variable based on plugin complexity) — Application startup waits for all plugins to initialize and resolve their dependencies
Control Points
- NODE_ENV Production Mode (env-var) — Controls: Error message verbosity and stack trace inclusion in responses. Default: detected from environment
- Adapter Selection (architecture-switch) — Controls: Which runtime adapter is used for request handling (Bun, Web Standard, Cloudflare Worker). Default: runtime-detected
- Cookie Secrets (runtime-toggle) — Controls: Whether cookies are signed and which secret is used for HMAC signing. Default: configurable per app
- Sucrose GC Time (threshold) — Controls: When to clear analysis cache to free memory during idle periods. Default: 4 minutes 55 seconds
Technology Stack
Provides compile-time type safety, complex type inference for request/response schemas, and enables static analysis optimizations
JSON Schema-based validation library that generates both TypeScript types and runtime validators from schema definitions
Primary target runtime providing native HTTP server, WebSocket support, and optimized JavaScript execution for the BunAdapter
Request/Response interfaces that enable cross-runtime compatibility through the WebStandardAdapter
Cookie parsing and serialization library used by the cookie management system for HTTP cookie handling
Efficient route matching library that handles path parameters, wildcards, and route prioritization
Key Components
- Elysia (orchestrator) — Main framework class that registers routes, compiles handlers, manages plugins, and coordinates the entire request/response lifecycle
src/index.ts - BunAdapter (adapter) — Bun-specific adapter that creates native Bun.serve() handlers, handles WebSocket upgrades, and optimizes for Bun's APIs
src/adapter/bun/index.ts - WebStandardAdapter () — Generic Web Standards adapter that works with Request/Response objects for compatibility across runtimes
src/adapter/web-standard/index.ts - getSchemaValidator (factory) — Creates ElysiaTypeCheck validators from schema definitions, handling both TypeBox schemas and StandardSchema v1 compatible validators
src/schema.ts - composeHandler (processor) — Compiles route handlers and lifecycle hooks into optimized JavaScript functions that handle the complete request pipeline
src/compose.ts - Sucrose (optimizer) — Static analysis system that examines handler functions to determine which context properties are used, enabling compile-time optimizations
src/sucrose.ts - separateFunction (transformer) — Parses stringified function code to extract parameters and body, supporting both arrow functions and regular functions for code analysis
src/sucrose.ts - Cookie (serializer) — Handles cookie parsing, serialization, signing/unsigning with secrets, and provides type-safe cookie access through context
src/cookies.ts - ValidationError (validator) — Creates detailed validation error responses with schema violations, supporting both TypeBox and StandardSchema error formats
src/error.ts - TraceHandler (monitor) — Provides detailed timing and execution tracing for each lifecycle stage, enabling performance monitoring and debugging
src/trace.ts
Explore the interactive analysis
See the full architecture map, data flow, and code patterns visualization.
Analyze on CodeSeaRelated 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 Karolina Sarna.