This CORS Mistake Exposes Your API (I See It Everywhere)
Source: Dev.to
Problem
A common pattern seen in many Cloudflare Workers (and other serverless functions) is:
headers.set('Access-Control-Allow-Origin', '*');
headers.set('Access-Control-Allow-Credentials', 'true');
At first glance this looks harmless, but it creates a serious security vulnerability.
Why it’s a security hole
When Access-Control-Allow-Origin is set to * and Access-Control-Allow-Credentials is set to true, you are telling browsers:
“Allow ANY website to make authenticated requests to my API.”
Consequences
- Malicious sites can read user data.
- They can issue requests on behalf of logged‑in users.
- Session tokens and cookies can be stolen.
Fixes
Option 1: Use specific origins
const allowedOrigins = [
'https://yourdomain.com',
'https://app.yourdomain.com'
];
const origin = request.headers.get('Origin');
if (allowedOrigins.includes(origin)) {
headers.set('Access-Control-Allow-Origin', origin);
headers.set('Access-Control-Allow-Credentials', 'true');
}
Only the listed origins are permitted to send credentialed requests.
Option 2: Omit credentials
If your API does not need cookies or other authentication headers, drop the credentials header entirely:
headers.set('Access-Control-Allow-Origin', '*');
// No Access-Control-Allow-Credentials header
Bottom line
Never use a wildcard (*) for Access-Control-Allow-Origin together with Access-Control-Allow-Credentials. Choose one approach—specific origins or no credentials. This simple change prevents a widespread CORS security mistake.