Middleware Stack

Backend middleware execution order. The sequence is critical for security — changing the order can introduce vulnerabilities.

Execution Order

#MiddlewarePurpose
1Request LoggingAssigns request UUID, logs method/path/timing
2Timeout55s limit (before 60s Fly.io LB timeout)
3Security HeadersCSP, X-Frame-Options, HSTS, X-Content-Type-Options
4CORSConfigurable origin allowlist per environment
5CSRF ProtectionOrigin validation on state-changing requests (POST/PUT/DELETE)
6Input SanitizationXSS/injection prevention via DOMPurify
7Rate LimitingGeneral: 100/min, Auth endpoints: 5/15min
8API SecurityJWT validation, token extraction
9Pretty JSONDevelopment-only formatted JSON responses

Rule: Security CORS Sanitization Rate Limiting Routes. See Coding Guidelines.

Middleware Files

All middleware in backend/src/middleware/ (10 files):

FileType
auth.tsAuthentication — JWT validation for internal users
portal-auth.tsPortal — token-based portal authentication
appointment-portal-auth.tsAppointments — appointment-specific portal auth
rbac.tsRBAC Authorization — role-based access control checks
sanitization.tsInput sanitization — see Validation Pattern
security.tsSecurity headers (CSP, HSTS, X-Frame-Options)
errorHandler.tsCentralized error handling — see Error Handling Pattern
rateLimiter.tsRate limiting with Redis-backed sliding window
timeout.tsRequest timeout enforcement
auditLogger.tsAudit Logs — records state-changing operations

Auth Middleware Variants

Three auth middlewares for different access patterns:

MiddlewareAudienceToken Source
auth.tsInternal users (employees)JWT Bearer token
portal-auth.tsExternal Portal usersPortal access token
appointment-portal-auth.tsAppointment portal visitorsShort-lived appointment token

Rate Limiting

Endpoint TypeLimitWindow
Authentication5 requests15 minutes
General API100 requests1 minute

Rate limiting uses Redis for distributed counting across instances.

See Also