CORS tells the browser whether JavaScript on one domain is allowed to communicate with an API on another domain. Bad configuration = broken frontend or security hole.
CORS headers¶
Access-Control-Allow-Origin: https://app.example.com Access-Control-Allow-Methods: GET, POST, PUT, DELETE Access-Control-Allow-Headers: Content-Type, Authorization Access-Control-Allow-Credentials: true
Configuration — Express.js¶
const cors = require(‘cors’); const allowed = [‘https://app.example.com’, ‘https://admin.example.com’]; app.use(cors({ origin: (origin, cb) => { if (!origin || allowed.includes(origin)) cb(null, true); else cb(new Error(‘Not allowed’)); }, credentials: true, })); // ❌ NEVER: cors({ origin: ‘*‘, credentials: true })
Common Mistakes¶
- Wildcard with credentials — does not work
- Origin reflection without validation
- Null origin allowed
Key Takeaway¶
Whitelist specific origins, never use wildcard with credentials.