Middleware Stack
Backend middleware execution order. The sequence is critical for security — changing the order can introduce vulnerabilities.
Execution Order
| # | Middleware | Purpose |
|---|---|---|
| 1 | Request Logging | Assigns request UUID, logs method/path/timing |
| 2 | Timeout | 55s limit (before 60s Fly.io LB timeout) |
| 3 | Security Headers | CSP, X-Frame-Options, HSTS, X-Content-Type-Options |
| 4 | CORS | Configurable origin allowlist per environment |
| 5 | CSRF Protection | Origin validation on state-changing requests (POST/PUT/DELETE) |
| 6 | Input Sanitization | XSS/injection prevention via DOMPurify |
| 7 | Rate Limiting | General: 100/min, Auth endpoints: 5/15min |
| 8 | API Security | JWT validation, token extraction |
| 9 | Pretty JSON | Development-only formatted JSON responses |
Rule: Security → CORS → Sanitization → Rate Limiting → Routes. See Coding Guidelines.
Middleware Files
All middleware in backend/src/middleware/ (10 files):
| File | Type |
|---|---|
auth.ts | Authentication — JWT validation for internal users |
portal-auth.ts | Portal — token-based portal authentication |
appointment-portal-auth.ts | Appointments — appointment-specific portal auth |
rbac.ts | RBAC Authorization — role-based access control checks |
sanitization.ts | Input sanitization — see Validation Pattern |
security.ts | Security headers (CSP, HSTS, X-Frame-Options) |
errorHandler.ts | Centralized error handling — see Error Handling Pattern |
rateLimiter.ts | Rate limiting with Redis-backed sliding window |
timeout.ts | Request timeout enforcement |
auditLogger.ts | Audit Logs — records state-changing operations |
Auth Middleware Variants
Three auth middlewares for different access patterns:
| Middleware | Audience | Token Source |
|---|---|---|
auth.ts | Internal users (employees) | JWT Bearer token |
portal-auth.ts | External Portal users | Portal access token |
appointment-portal-auth.ts | Appointment portal visitors | Short-lived appointment token |
Rate Limiting
| Endpoint Type | Limit | Window |
|---|---|---|
| Authentication | 5 requests | 15 minutes |
| General API | 100 requests | 1 minute |
Rate limiting uses Redis for distributed counting across instances.
See Also
- Backend Middleware — detailed middleware documentation
- Backend Architecture — overall backend structure
- Authentication — auth flow details
- RBAC Authorization — permission checks
- Validation Pattern — sanitization details
- Error Handling Pattern — error handler behavior