CORS Configuration
Browser-enforced HTTP headers that control which origins, methods, and headers are allowed to make cross-origin requests to an API.
Description
Cross-Origin Resource Sharing (CORS) is a browser security mechanism that restricts web pages from making requests to a different origin (domain, protocol, or port) than the one that served the page. When a frontend at app.example.com needs to call an API at api.example.com, the browser first sends a preflight OPTIONS request to check whether the API allows cross-origin access. The server must respond with appropriate CORS headers (Access-Control-Allow-Origin, Access-Control-Allow-Methods, Access-Control-Allow-Headers) for the browser to permit the actual request.
CORS configuration must be precise: Access-Control-Allow-Origin should list specific allowed origins rather than using the wildcard (*), especially for APIs that accept credentials (cookies, Authorization headers). Wildcards and credentials are mutually exclusive per the spec. The Access-Control-Allow-Methods header specifies which HTTP methods are permitted, and Access-Control-Allow-Headers lists which request headers are allowed. The Access-Control-Max-Age header controls how long browsers cache preflight responses, reducing the overhead of preflight requests.
Common CORS mistakes include overly permissive configurations (allowing all origins in production), forgetting to handle the OPTIONS preflight method, not exposing custom response headers via Access-Control-Expose-Headers (clients can't read X-Request-Id or X-RateLimit-Remaining without this), and inconsistent configuration between environments. CORS should be configured at the API gateway or reverse proxy level for consistency, and tested with integration tests that verify preflight behavior for all supported origins.
Prompt Snippet
Configure CORS at the API gateway layer with an explicit origin allowlist loaded from environment config (e.g., ALLOWED_ORIGINS=https://app.example.com,https://staging.example.com). Set Access-Control-Allow-Credentials: true and never use Access-Control-Allow-Origin: * with credentialed requests. Expose custom headers via Access-Control-Expose-Headers: X-Request-Id, X-RateLimit-Remaining, X-RateLimit-Limit. Set Access-Control-Max-Age: 86400 to cache preflight responses for 24 hours. Add integration tests that verify preflight OPTIONS responses for allowed and disallowed origins.
Tags
Related Terms
API Gateway Pattern
A single entry point that sits in front of backend services to handle cross-cutting concerns like authentication, rate limiting, routing, and request transformation.
API Authentication Patterns
Methods for verifying the identity of API consumers, including API keys, OAuth 2.0 Bearer tokens, JWTs, and mutual TLS.
REST API Conventions
A set of architectural constraints and naming conventions for designing consistent, predictable HTTP APIs around resources.