patternpythonMajorpending
CORS configuration for production APIs
Viewed 0 times
corscross-originpreflightaccess-controlcredentials
Problem
Need to properly configure CORS headers for a production API that serves multiple frontends.
Solution
Never use wildcard (*) with credentials. Configure explicitly:
Checklist:
# Python/Flask
from flask_cors import CORS
ALLOWED_ORIGINS = [
'https://app.example.com',
'https://admin.example.com',
]
CORS(app,
origins=ALLOWED_ORIGINS,
methods=['GET', 'POST', 'PUT', 'DELETE'],
allow_headers=['Content-Type', 'Authorization'],
expose_headers=['X-Request-Id'],
supports_credentials=True,
max_age=3600) # Cache preflight for 1 hour// Node/Express
const cors = require('cors');
app.use(cors({
origin: (origin, callback) => {
if (!origin || ALLOWED_ORIGINS.includes(origin)) {
callback(null, true);
} else {
callback(new Error('CORS not allowed'));
}
},
credentials: true,
maxAge: 3600
}));Checklist:
- Whitelist specific origins (never * with credentials)
- Set max_age to reduce preflight requests
- Only expose needed headers
- Handle null origin for non-browser clients
Why
Misconfigured CORS can either block legitimate requests or expose your API to cross-origin attacks.
Gotchas
- Access-Control-Allow-Origin: * cannot be used with credentials
- Preflight OPTIONS requests need same CORS headers
- Some CDNs strip Vary: Origin header, breaking CORS
Context
API serving requests from web frontends on different domains
Revisions (0)
No revisions yet.