CORS
The Golden Rule: Avoid the Wildcard (*)
*)Best Practice Implementation
npm install corsconst express = require('express');
const cors = require('cors');
const app = express();
// 1. Define the whitelist
// In production, these should ideally come from process.env variables
const allowedOrigins = [
'https://www.yoursite.com',
'https://admin.yoursite.com',
'http://localhost:3000' // Useful for local development
];
// 2. Configure CORS options
const corsOptions = {
origin: (origin, callback) => {
// Check if the origin is in the whitelist
// !origin allows requests without an Origin header (e.g., Postman, mobile apps, or server-to-server)
if (allowedOrigins.indexOf(origin) !== -1 || !origin) {
callback(null, true);
} else {
callback(new Error('Not allowed by CORS'));
}
},
methods: ['GET', 'POST', 'PUT', 'DELETE'], // Explicitly allow only needed methods
allowedHeaders: ['Content-Type', 'Authorization'], // Explicitly allow only needed headers
credentials: true, // Allow cookies/session headers to be sent
optionsSuccessStatus: 200 // Legacy browser support (some choke on 204)
};
// 3. Apply the Middleware
// Apply globally to all routes
app.use(cors(corsOptions));
// Optional: Enable pre-flight requests for all routes
app.options('*', cors(corsOptions));
app.get('/api/data', (req, res) => {
res.json({ message: 'This data is CORS-enabled for whitelisted domains.' });
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});Key Breakdown of Settings
Handling Errors
Last updated