JAVASCRIPT
Secure CORS Configuration for REST APIs in Node.js
Implement a secure Cross-Origin Resource Sharing (CORS) policy for your Node.js REST API to control which domains can make requests, enhancing security and preventing unauthorized access.
const express = require('express');
const cors = require('cors');
const app = express();
const allowedOrigins = ['https://www.your-frontend.com', 'http://localhost:3000'];
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', 'POST', 'PUT', 'DELETE'],
allowedHeaders: ['Content-Type', 'Authorization'],
credentials: true, // Allow cookies to be sent with requests
optionsSuccessStatus: 200 // Some legacy browsers (IE11, various SmartTVs) choke on 204
};
// Apply CORS middleware
app.use(cors(corsOptions));
app.get('/api/data', (req, res) => {
res.json({ message: 'This is secure data!' });
});
app.listen(3001, () => {
console.log('API Server running on port 3001 with secure CORS');
});
How it works: Cross-Origin Resource Sharing (CORS) is a security mechanism that allows web browsers to relax the same-origin policy, permitting controlled access to resources located outside of a given domain. This snippet demonstrates how to configure CORS securely in a Node.js Express API using the 'cors' middleware. It defines a whitelist of `allowedOrigins` and custom logic to validate incoming requests, ensuring only trusted frontends can interact with the API, thereby preventing unauthorized cross-origin requests and potential data leakage.