Skip to content

CORS(CORS)

What is CORS?

CORS (Cross-Origin Resource Sharing) is a security mechanism enforced by web browsers that controls how web pages from one origin (domain, protocol, and port) can request resources from a different origin. By default, browsers implement a same-origin policy that blocks cross-origin HTTP requests initiated from scripts. CORS provides a standardized way for servers to declare which origins are permitted to access their resources, enabling safe cross-origin data sharing while maintaining security.

How CORS Works

When a browser makes a cross-origin request, it includes an Origin header indicating where the request originated. For simple requests (basic GET or POST with standard headers), the browser sends the request directly and checks the response for an Access-Control-Allow-Origin header. For more complex requests — those using custom headers, non-standard methods like PUT or DELETE, or certain content types — the browser first sends a preflight OPTIONS request to ask the server whether the actual request is permitted. The server responds with CORS headers specifying allowed origins, methods, headers, and whether credentials can be included.

Common CORS Headers

The key CORS response headers include Access-Control-Allow-Origin (which origins can access the resource), Access-Control-Allow-Methods (which HTTP methods are permitted), Access-Control-Allow-Headers (which request headers are allowed), Access-Control-Max-Age (how long preflight results can be cached), and Access-Control-Allow-Credentials (whether cookies and authentication headers are permitted). Misconfiguring these headers is a frequent source of bugs during API development, often resulting in opaque browser errors that can be difficult to diagnose.

CORS in API Development

For API developers, CORS configuration is essential when building APIs consumed by browser-based applications. Backend frameworks and API gateways typically provide middleware to configure CORS policies. A common pattern is to allow specific trusted origins in production while permitting broader access in development environments. Using a wildcard (*) for Access-Control-Allow-Origin is convenient but prevents the use of credentials and may expose the API to unintended consumers. Thoughtful CORS configuration balances developer experience with security requirements.

Termes associés