Blog
Express and Fastify CORS middleware: patterns for production APIs
Compare popular middleware options, dynamic origin functions, and how to avoid middleware ordering issues.
1 min read
nodejsexpressfastifycors
Dynamic origin callbacks
Use a function that validates Origin against a database-backed allowlist for multi-tenant SaaS APIs.
Return false or a callback error to deny; never reflect arbitrary Origin strings without validation.
Performance and observability
Short-circuit OPTIONS with minimal work in hot paths; log denials at info level with origin and route.
Add metrics for preflight count versus total requests to detect misconfigured clients.
