JAVASCRIPT
Secure CORS Configuration in Node.js Express
Properly configure Cross-Origin Resource Sharing (CORS) in Express.js applications to restrict access to trusted origins, enhancing API security and preventing unauthorized data access.
const express = require('express');
const cors = require('cors');
const app = express();
// Define a list of allowed origins
const allowedOrigins = [
'http://localhost:3000',
'https://your-frontend-domain.com',
'https://another-trusted-domain.org'
];
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',
credentials: true, // Allow cookies to be sent
optionsSuccessStatus: 204 // Some legacy browsers (IE11, various SmartTVs) choke on 200
};
// Apply CORS middleware with options
app.use(cors(corsOptions));
// Example route
// app.get('/data', (req, res) => {
// res.json({ message: 'This data is protected by CORS.' });
// });
// app.listen(8080, () => {
// console.log('Server running on port 8080');
// });
How it works: This snippet demonstrates how to securely configure Cross-Origin Resource Sharing (CORS) in an Express.js application using the `cors` middleware. Instead of simply allowing all origins (`*`), it defines a whitelist of `allowedOrigins`. The `origin` function in `corsOptions` checks if the incoming request's origin is in this whitelist. Requests without an origin (e.g., from Postman or certain server-side requests) are also allowed. It also explicitly specifies allowed HTTP methods and sets `credentials: true` to enable sending cookies with cross-origin requests, which is crucial for session-based authentication. This strict configuration prevents untrusted domains from making requests to your API, significantly reducing the risk of cross-site request forgery (CSRF) and data leakage.