What is CORS?
CORS (Cross-Origin Resource Sharing) is a security mechanism that allows web browsers to make requests to servers on different domains than the one serving the web page. It uses HTTP headers to tell browsers which cross-origin requests should be permitted.
Quick Facts
| Full Name | Cross-Origin Resource Sharing |
|---|---|
| Created | 2004 (initial proposal), 2014 (W3C Recommendation) |
| Specification | Official Specification |
How CORS Works
CORS was developed to relax the Same-Origin Policy, which by default prevents web pages from making requests to different domains. When a browser makes a cross-origin request, it first sends a preflight OPTIONS request to check if the server allows the actual request. The server responds with CORS headers indicating which origins, methods, and headers are permitted. CORS is essential for modern web applications that consume APIs from different domains. Misconfigured CORS can lead to security vulnerabilities or blocked requests.
Key Characteristics
- Relaxes Same-Origin Policy restrictions
- Uses HTTP headers for access control
- Preflight requests check permissions
- Controlled by server-side configuration
- Supports credentials (cookies, auth headers)
- Can specify allowed origins, methods, headers
Common Use Cases
- Consuming third-party APIs
- Microservices architecture
- CDN resource loading
- Single-page applications
- Cross-domain font loading
Example
CORS Response Headers:
Access-Control-Allow-Origin: https://example.com
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Allow-Credentials: true
Access-Control-Max-Age: 86400
Preflight Request:
OPTIONS /api/data HTTP/1.1
Origin: https://example.com
Access-Control-Request-Method: POST
Access-Control-Request-Headers: Content-Type
Preflight Response:
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://example.com
Access-Control-Allow-Methods: POST
Access-Control-Allow-Headers: Content-Type
Node.js/Express CORS:
app.use(cors({
origin: 'https://example.com',
methods: ['GET', 'POST'],
credentials: true
}));