What Is CORS (Cross-Origin Resource Sharing)?
CORS (Cross-Origin Resource Sharing) is a browser security mechanism that controls which websites can make requests to your server. By default, browsers block cross-origin requests (Same-Origin Policy). CORS headers let you selectively allow specific origins to access your API, while keeping everyone else blocked.
Types of CORS (Cross-Origin Resource Sharing)?
Simple Requests
GET, HEAD, or POST with standard headers — sent directly with an Origin header. The browser checks the response for Access-Control-Allow-Origin.
Preflight Requests
For non-simple requests (PUT, DELETE, custom headers), the browser sends an OPTIONS preflight first to check if the server allows the actual request.
Credentialed Requests
Requests with cookies or auth headers require Access-Control-Allow-Credentials: true and a specific origin (not wildcard *).
How to Prevent It
# Secure CORS configuration — Express.js
const allowedOrigins = ['https://myapp.com', 'https://admin.myapp.com'];
app.use((req, res, next) => {
const origin = req.headers.origin;
if (allowedOrigins.includes(origin)) {
res.setHeader('Access-Control-Allow-Origin', origin);
res.setHeader('Access-Control-Allow-Credentials', 'true');
}
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
res.setHeader('Access-Control-Max-Age', '86400');
if (req.method === 'OPTIONS') return res.sendStatus(204);
next();
});
# DANGEROUS — never do this in production:
# Access-Control-Allow-Origin: *
# Access-Control-Allow-Credentials: true
# (These two together are actually blocked by browsers)
Real-World Impact
Misconfigured CORS (especially reflecting any Origin with credentials) allows any website to make authenticated requests to your API, stealing user data, performing unauthorized actions, and exfiltrating sensitive information.
Related Questions
Scan your system prompt with LochBot — free, client-side, no data sent anywhere.