Backend Middleware
10 middleware modules in backend/src/middleware/. Execution order is critical — security middleware runs before business logic, and error handling wraps everything.
Middleware Pipeline
| Order | File | Purpose | Config |
|---|---|---|---|
| 1 | (built-in) | Request logging + UUID | Hono logger |
| 2 | timeout.ts | 55-second request timeout | Prevents hung requests |
| 3 | security.ts | CSP, HSTS, X-Frame-Options headers | Middleware Stack |
| 4 | (built-in) | CORS | Hono CORS |
| 5 | sanitization.ts | XSS/injection prevention via DOMPurify | Validation Pattern |
| 6 | rateLimiter.ts | Auth: 5 req/15min, API: 100 req/min | Upstash Redis |
| 7 | auth.ts | JWT verification and user context | Authentication |
| 8 | rbac.ts | Role-based access control checks | RBAC Authorization |
| 9 | portal-auth.ts | Portal token authentication | Portal |
| 10 | appointment-portal-auth.ts | Appointment portal token auth | Appointments |
| 11 | auditLogger.ts | Audit trail logging | Audit Logs |
| 12 | errorHandler.ts | Centralized error handling + Sentry capture | Error Handling Pattern |
Middleware Order Rule
The order in backend/src/index.ts must follow:
security → cors → sanitization → rateLimiter → routes
Changing order can break security guarantees. See Middleware Stack for rationale.
Auth Middleware
Two authentication strategies:
| Strategy | Middleware | Token Type | Used By |
|---|---|---|---|
| Session | auth.ts | JWT (httpOnly cookie) | Main app routes |
| Portal | portal-auth.ts | Portal token (URL param) | Portal routes |
| Appointment | appointment-portal-auth.ts | Appointment token | Appointments portal |
Rate Limiting
| Endpoint Group | Limit | Window |
|---|---|---|
Auth routes (/api/auth/*) | 5 requests | 15 minutes |
| General API | 100 requests | 1 minute |
Backed by Upstash Redis. See Backend Architecture for Redis infrastructure.
Error Handler
errorHandler.ts catches all unhandled errors and:
- Logs the error with request context
- Reports to Sentry (with sensitive data scrubbing)
- Returns a structured JSON error response
See Error Handling Pattern for error response format.
Sanitization
sanitization.ts runs DOMPurify on all request body fields. Three sanitization levels:
| Level | Allowed Tags | Use Case |
|---|---|---|
STRICT | None (strips all HTML) | 99% of user input |
BASIC_FORMATTING | <b>, <i>, <em>, <strong>, <br> | Rich text fields |
RICH_TEXT | Extended set | Admin-only, never user input |
Related
- Middleware Stack — Full middleware architecture documentation
- Authentication — JWT auth flow details
- RBAC Authorization — Role-based access control
- Error Handling Pattern — Structured error responses
- Sentry — Error tracking integration
- Backend Architecture — Where middleware fits in the stack