TL;DR
CORS (Cross-Origin Resource Sharing) controls which websites can make requests to your API. A misconfigured CORS policy can let attackers steal user data from malicious websites. Never use Access-Control-Allow-Origin: * with credentials, and always validate origins against an allowlist.
What Is CORS?
CORS is a browser security feature that restricts web pages from making requests to a different domain than the one serving the page. Your server tells browsers which origins are allowed to access your API through response headers.
Common CORS Mistakes
// VULNERABLE: Reflects whatever origin is sent
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', req.headers.origin);
res.header('Access-Control-Allow-Credentials', 'true');
next();
});
// Attacker's site can now read authenticated responses!
Critical mistake: Reflecting the Origin header while allowing credentials means any website can make authenticated requests to your API and read the responses.
Other Dangerous Patterns
Access-Control-Allow-Origin: *with sensitive data- Regex matching that can be bypassed:
/\.yoursite\.com$/matchesevilyoursite.com - Allowing
nullorigin (used by sandboxed iframes) - Trusting subdomains when any subdomain could be compromised
Secure CORS Configuration
const allowedOrigins = [
'https://yoursite.com',
'https://app.yoursite.com'
];
app.use((req, res, next) => {
const origin = req.headers.origin;
if (allowedOrigins.includes(origin)) {
res.header('Access-Control-Allow-Origin', origin);
res.header('Access-Control-Allow-Credentials', 'true');
}
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
next();
});
Can I use * if I don't use cookies?
Using * is safe for truly public APIs with no authentication. But if you use any form of auth (tokens in headers, API keys), you should restrict origins.
Why does CORS only apply to browsers?
CORS is enforced by browsers to protect users. Server-to-server requests or curl bypass CORS entirely. It prevents malicious websites from using the user's browser as a proxy.
What about preflight requests?
Browsers send OPTIONS requests before certain cross-origin requests. Make sure your server handles OPTIONS and returns the correct CORS headers.
Check Your CORS Config
Our scanner tests your CORS headers for common misconfigurations.
Start Free Scan