Core Concepts
Middleware System
Middleware that orders itself. Type-safe context passing and automatic optimization — write middleware, we handle the rest.
Overview
Write your middleware. We order it optimally. Authentication before authorization. Validation early. Caching smart.
Automatic Ordering
- 1Request parsing
- 2Authentication
- 3Authorization
- 4Validation
- 5Rate limiting
- 6Caching
- 7Handler execution
Benefits
- Automatic optimization
- Type-safe context
- Early exit on errors
- Composable design
- Performance optimized
Traditional frameworks make you manually order middleware. We do that automatically based on dependencies and performance. Without intelligent ordering, you're manually managing execution order, risking bugs, and missing optimization opportunities.
Traditional Frameworks
- Manual middleware ordering
- Easy to get order wrong
- No automatic optimization
- Type safety requires extra work
With MoroJS
- Automatic middleware ordering
- Optimal execution path
- Type-safe context passing
- Performance optimized automatically
Add middleware globally or to specific routes. Ordering is automatic.
Global Middleware
typescript
Route-Specific Middleware
typescript
Automatic Ordering
Middleware runs in the right order automatically. No manual configuration needed.
Type Safe
Context is fully typed. TypeScript knows what's available in your handlers.
Optimized
Execution paths are optimized automatically. Maximum performance.
How It Works
MoroJS analyzes your middleware at startup and creates an optimized execution plan. Middleware is automatically ordered based on dependencies, type-safe context is passed between middleware, and execution paths are optimized for maximum performance.
Global Middleware
Global middleware runs on every request and is perfect for logging, CORS, and other cross-cutting concerns.
Global Middleware Example
typescript
Route-Specific Middleware
Authentication Middleware
typescript
Multiple Middleware - Chainable API
typescript
Built-in Middleware Options
typescript
Body Parsers — json() & urlencoded()
MoroJS auto-parses JSON bodies upstream, so json() is a pass-through that exists purely for Express-style app.use(json()) compatibility. urlencoded() decodes application/x-www-form-urlencoded bodies into req.body.
Importing and mounting
typescript
When you actually need these
- • Migrating Express code that calls
app.use(json())— works verbatim - • Accepting HTML form submissions (
urlencoded) - • For pure JSON APIs, you can skip
json()entirely — MoroJS parses bodies automatically
Options
typescript
Creating Custom Middleware
Custom Middleware Pattern
typescript
Conditional Middleware & Middleware Factories
typescript