Strict CORS & Preflight Response Headers for Cloudflare Workers
Implement watertight Cross-Origin Resource Sharing (CORS) with origin whitelisting and credentials support for serverless APIs.
1. Attack Signature & Impact Analysis
Medium (Cross-Site Data Leak)Lazy wildcard `Access-Control-Allow-Origin: *` headers combined with cookie authentication allow malicious third-party websites to make background requests on behalf of victims.
2. Production Hardening Configuration (worker.js / index.ts)
Deploy this validated configuration to your production server or reverse proxy:
// Cloudflare Worker Strict CORS Implementation
const ALLOWED_ORIGINS = ['https://app.yourdomain.com', 'https://yourdomain.com'];
export default {
async fetch(request) {
const origin = request.headers.get('Origin');
const isAllowed = ALLOWED_ORIGINS.includes(origin);
// Handle CORS Preflight OPTIONS request
if (request.method === 'OPTIONS') {
return new Response(null, {
headers: {
'Access-Control-Allow-Origin': isAllowed ? origin : ALLOWED_ORIGINS[0],
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
'Access-Control-Max-Age': '86400',
}
});
}
const response = await handleAPI(request);
response.headers.set('Access-Control-Allow-Origin', isAllowed ? origin : ALLOWED_ORIGINS[0]);
return response;
}
};
3. Live Simulation & Rule Verification Command
Execute these commands to verify that traffic is actively mitigated without service downtime:
# Test CORS preflight with curl
curl -X OPTIONS https://api.yourdomain.com/data \
-H "Origin: https://app.yourdomain.com" \
-H "Access-Control-Request-Method: POST" -I
4. Common Misconfigurations & Troubleshooting Gotchas
⚠️ Production Caution: Never reflect arbitrary Origin headers blindly without validating against an explicit whitelist array.
5. Best Paired With (Complementary Defense Recipes)
Security engineers implementing this rule frequently deploy these complementary baselines: