JAVASCRIPT
Configure Cross-Origin Resource Sharing (CORS) Securely
Properly configure CORS in your Node.js Express API to control which origins can access your resources, preventing unauthorized cross-domain requests.
const express = require('express');
const cors = require('cors');
const app = express();
// Option 1: Allow all origins (NOT recommended for production APIs)
// app.use(cors());
// Option 2: Allow specific origins (Recommended for production)
const allowedOrigins = ['http://localhost:3000', 'https://yourfrontend.com'];
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 with cross-origin requests
optionsSuccessStatus: 204 // Some legacy browsers (IE11, various SmartTVs) choke on 200
};
app.use(cors(corsOptions));
app.get('/data', (req, res) => {
res.json({ message: 'This is secure data!' });
});
app.listen(3001, () => console.log('CORS-enabled web server listening on port 3001'));
How it works: This snippet demonstrates how to securely configure Cross-Origin Resource Sharing (CORS) in a Node.js Express application. CORS is a security mechanism that allows a web page from one domain to access a resource in another domain. While `app.use(cors())` allows all origins, it's highly insecure for production. The recommended approach is to define `allowedOrigins` to explicitly whitelist domains that are permitted to make requests to your API. This prevents unauthorized websites from making requests on behalf of your users, thereby protecting your API from certain types of attacks, such as basic CSRF if combined with proper credential handling. The `credentials: true` option allows cookies or authorization headers to be sent with cross-origin requests.