What is CORS?
CORS (Cross-Origin Resource Sharing) is a security mechanism that controls how web pages from one origin can request resources from another origin.
What is an Origin?
An origin is the combination of:
https://app.example.com:443
│ │ │
protocol host port
Same-origin = all three match. Cross-origin = any differs.
The Same-Origin Policy
Browsers enforce the Same-Origin Policy (SOP):
- JavaScript from
https://app.example.comcan only read responses fromhttps://app.example.com - Requests to
https://api.example.comare blocked unless CORS allows them
Browser:
┌─────────────────────────────────────────┐
│ JavaScript from https://app.example.com │
│ │
│ fetch('https://api.example.com/data') │
│ │ │
│ v │
│ CORS Check: │
│ Does api.example.com allow │
│ app.example.com? │
│ │
│ YES → Allow response │
│ NO → Block response (CORS error) │
└─────────────────────────────────────────┘
CORS Headers
Response from API server:
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Max-Age: 86400
CORS Preflight
For non-simple requests, the browser sends a preflight OPTIONS request:
Browser Server
| |
| OPTIONS /api/data |
| Origin: https://app.example.com|
| Access-Control-Request-Method: |
| POST |
| Access-Control-Request-Headers:|
| Content-Type, Authorization |
|------------------------------->|
| |
| 204 No Content |
| Access-Control-Allow-Origin: |
| https://app.example.com |
| Access-Control-Allow-Methods: |
| GET, POST, PUT, DELETE |
|<-------------------------------|
| |
| POST /api/data |
| Content-Type: application/json |
| Authorization: Bearer ... |
|------------------------------->|
| |
| 200 OK + JSON response |
|<-------------------------------|
CORS Implementation
Backend Configuration
Express.js:
const cors = require('cors');
app.use(cors({
origin: 'https://app.example.com',
methods: ['GET', 'POST', 'PUT', 'DELETE'],
allowedHeaders: ['Content-Type', 'Authorization'],
credentials: true,
maxAge: 86400
}));
Spring Boot:
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("https://app.example.com")
.allowedMethods("GET", "POST", "PUT", "DELETE")
.allowedHeaders("*")
.allowCredentials(true);
}
}
Common CORS Errors
| Error | Cause | Fix |
|---|---|---|
| No 'Access-Control-Allow-Origin' | Missing CORS config | Add CORS headers |
| Origin not allowed | Origin not in whitelist | Add origin to allowed list |
| Method not allowed | Request method not permitted | Add method to allowed list |
| Credentials not allowed | credentials: true without specific origin | Use specific origin, not * |
Practice Problems
Design and implement a solution for CORS in a backend system. Consider scalability, error handling, and production readiness.
Solution
// CORS implementation
// Key aspects: validation, error handling, logging, testing
public class CORS {
// Production-ready implementation
}Identify and handle edge cases for CORS. What happens under high load, with invalid input, or during failures?
Solution
// Edge case handling:
// 1. Null/empty input -> validation
// 2. High load -> rate limiting, queuing
// 3. Failures -> retries, circuit breaker
// 4. Concurrent access -> locks, idempotencyWrite a testing strategy for CORS. Include unit tests, integration tests, and performance tests.
Solution
// Test plan:
// - Unit: 80% coverage target
// - Integration: API contracts
// - Performance: latency, throughput
// - Chaos: failure injectionQuiz
1. Why was CORS introduced?
2. What HTTP method does the browser send for CORS preflight?
3. What is the primary purpose of CORS?
4. What is a common mistake when implementing CORS?
Flashcards
Question
What is CORS?
Click to reveal answer
Answer
Cross-Origin Resource Sharing — controls cross-origin HTTP requests
Question
What triggers a CORS preflight?
Click to reveal answer
Answer
Non-simple requests (custom headers, non-GET methods) trigger OPTIONS preflight
Question
What is CORS?
Click to reveal answer
Answer
CORS is a key concept in backend development.
Question
When to use CORS?
Click to reveal answer
Answer
Use CORS when building production systems that require reliability, scalability, and maintainability.
Question
CORS best practices
Click to reveal answer
Answer
Follow SOLID principles, write clean code, test thoroughly, document decisions, and monitor in production.
Revision Notes
Key Takeaways
- 1.CORS controls cross-origin resource access
- 2.Same-Origin Policy blocks unauthorized cross-origin reads
- 3.Preflight (OPTIONS) checks permissions before actual request
- 4.Use specific origins, not wildcard * for credentials
Interview Tips
- •Explain why CORS exists and how it works
- •Know how to configure CORS in your framework
Cheat Sheet
CORS
- Purpose: Control cross-origin access
- Headers: Access-Control-Allow-Origin, Methods, Headers
- Preflight: OPTIONS request for non-simple requests
- Config: Use specific origin (not *) with credentials