JAVASCRIPT
Configure CORS Safely for Specific Origins in Express.js
Implement secure Cross-Origin Resource Sharing (CORS) in your Express.js API by whitelisting trusted origins, preventing unauthorized cross-domain requests and enhancing application security.
const express = require('express');
const cors = require('cors');
const app = express();
// Define a whitelist of allowed origins
const allowedOrigins = [
'http://localhost:8080', // Example development frontend
'https://www.your-production-domain.com' // Your actual production frontend
];
const corsOptions = {
origin: function (origin, callback) {
// Allow requests with no origin (like mobile apps or curl requests)
if (!origin) return callback(null, true);
if (allowedOrigins.indexOf(origin) === -1) {
const msg = 'The CORS policy for this site does not allow access from the specified Origin.';
return callback(new Error(msg), false);
}
return callback(null, true);
},
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE', // Allowed HTTP methods
credentials: true, // Allow cookies to be sent with cross-origin requests
optionsSuccessStatus: 204 // Some legacy browsers (IE11, various SmartTVs) choke on 200
};
// Use the CORS middleware with the defined options
app.use(cors(corsOptions));
app.get('/data', (req, res) => {
res.json({ message: 'This data is accessible from allowed origins!' });
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
How it works: This Express.js snippet configures Cross-Origin Resource Sharing (CORS) to enhance security by allowing access only from explicitly defined origins. The `cors` middleware is configured with an `origin` function that checks if the incoming request's origin is in the `allowedOrigins` whitelist. Requests from unlisted origins are blocked, preventing unauthorized cross-domain data access. It also specifies allowed HTTP methods and enables `credentials` to allow cookies to be sent, while setting `optionsSuccessStatus` for broader browser compatibility. This approach is crucial for securing APIs by controlling which frontends can interact with them.