Back to cheatsheets
Web Security
CORS Configuration
Configure Cross-Origin Resource Sharing safely — avoid wildcard origins with credentials.
What you'll learn
- Express.js CORS setup
- Common CORS misconfigurations
How to use these snippets
- Click the Copy button next to any snippet to copy it to your clipboard.
- Paste the code into your project, IDE, or terminal.
- Replace placeholder values (like
example.comoryour-secret) with your actual data. - Review the code comments for important security notes and caveats.
- Try the interactive related tool to see the concept in action.
Code Snippets
Copy-paste code snippets
2 ready-to-use snippets for cors configuration. Click copy and paste into your project.
Express.js CORS setup
const cors = require('cors');
// Allow specific origin with credentials
app.use(cors({
origin: 'https://example.com', // never '*' with credentials
credentials: true,
methods: ['GET', 'POST', 'PUT', 'DELETE'],
allowedHeaders: ['Content-Type', 'Authorization'],
maxAge: 86400 // cache preflight for 24h
}));
Common CORS misconfigurations
// ❌ DANGEROUS: wildcard with credentials
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
// Browsers block this, but some servers reflect the Origin
// header instead, which is equally dangerous.
// ❌ Origin reflection (dynamic ACAO)
const origin = req.headers.origin;
res.setHeader('Access-Control-Allow-Origin', origin);
// This allows ANY website to make authenticated requests.
// ✅ Allowlist specific origins
const ALLOWED = ['https://app.example.com', 'https://admin.example.com'];
const origin = req.headers.origin;
if (ALLOWED.includes(origin)) {
res.setHeader('Access-Control-Allow-Origin', origin);
res.setHeader('Vary', 'Origin');
}
Tool
Related ShieldX tool
Try this concept hands-on with the interactive tool.
100% Free · No signup · No cost
Generate something unguessable right now
148 bits of entropy, a crack-time estimate you can trust, and a clipboard that clears itself after 30 seconds.
Part of the Toolly ecosystem · secure.toolly.site