ServerMiddleware & Lifecycle
Overview
Middleware responsibilities, HandlerContext lifecycle, and execution order.
Middleware in the CRM server is the first line of defense for every HTTP request. It builds the HandlerContext, enforces authentication, runs lifecycle hooks, and provides request-scoped services.
Key Responsibilities
- Request Context: Add
requestId, timing metadata - Session Resolution: Resolve user from cookies
- Tenant Resolution: Resolve organization from header/API key
- Authentication: Block anonymous requests where required
- Lifecycle Hooks: Run before/after request hooks
Middleware Location
All middleware in lib/middleware/:
session.ts— Session resolutiontenant.ts— Tenant/org resolutionauth.ts— Route guardslifecycle.ts— Lifecycle hooks
Quick Navigation
- Architecture — Execution order and context building
- Middleware List — Detailed middleware inventory
- Lifecycle Hooks — Before/after hook patterns
- Runbook — Troubleshooting