In modern web applications, frontend and backend often live on different domains. This is where CORS (Cross-Origin Resource Sharing) becomes critical. Misconfigured CORS is one of the most common backend security mistakesβand one of the easiest to avoid if you understand it well.
This article explains best-practice CORS policies that every professional backend developer should follow.
π What Is CORS?
CORS is a browser security mechanism that controls how resources from one origin (domain) can be accessed by another origin.
π Important:
CORS is enforced by the browser, but configured by the backend.
β The Most Common CORS Mistake
Access-Control-Allow-Origin: *
This allows any website to call your API.
β οΈ If your API uses cookies, tokens, or sessions, this is a serious security risk.
β Best Practices for Secure CORS Configuration
1οΈβ£ Use an Allowlist of Trusted Origins
Always allow only known domains:
const allowedOrigins = [
'https://app.example.com',
'https://admin.example.com'
];
This prevents malicious websites from accessing your backend.
2οΈβ£ Never Use Wildcards with Credentials
If you use:
Cookies
JWT in headers
Sessions
Then you must specify exact origins.
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: https://app.example.com
β * is not allowed with credentials.
3οΈβ£ Limit Allowed HTTP Methods
Only allow what your API actually needs:
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Avoid allowing unused methods like PATCH or OPTIONS unnecessarily.
4οΈβ£ Restrict Allowed Headers
Explicitly define allowed headers:
Access-Control-Allow-Headers: Content-Type, Authorization
This reduces attack surface.
5οΈβ£ Handle Preflight (OPTIONS) Requests Properly
Browsers send OPTIONS requests before certain API calls.
βοΈ Best practice:
Respond quickly
No authentication required
Return 204 No Content
6οΈβ£ Environment-Based CORS Rules
| Environment | Policy |
|---|---|
| Development | Allow localhost
|
| Staging | Allow test domains |
| Production | Strict allowlist |
This keeps development easy and production secure.
7οΈβ£ Do Not Treat CORS as Security
CORS does NOT replace:
Authentication
Authorization
Rate limiting
Input validation
Attackers can still call your API directly using tools like Postman or curl.
π Example: Secure Node.js CORS Configuration
app.use(cors({
origin: ['https://app.example.com'],
methods: ['GET', 'POST', 'PUT', 'DELETE'],
allowedHeaders: ['Content-Type', 'Authorization'],
credentials: true,
maxAge: 86400
}));
π§ Interview Tip
Q: Is CORS a frontend or backend security feature?
A: CORS is enforced by the browser, but controlled by the backend.
This answer impresses interviewers.
π Final Thoughts
A good backend developer:
Uses least-privilege CORS
Avoids wildcards in production
Separates environment configurations
Understands CORS is not real security
Correct CORS configuration shows professional backend maturity.
Top comments (0)