JAVASCRIPT
Configuring Cross-Origin Resource Sharing (CORS) in Express.js
Securely enable Cross-Origin Resource Sharing (CORS) in your Express.js application, allowing only specified domains to access your API resources.
const express = require('express');
const cors = require('cors');
const app = express();
const allowedOrigins = ['https://www.myfrontend.com', 'http://localhost:8080'];
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: 200 // Some legacy browsers (IE11, various SmartTVs) choke on 204
};
// Use CORS middleware with specific options
app.use(cors(corsOptions));
app.get('/api/data', (req, res) => {
res.json({ message: 'This data is accessible from allowed origins.' });
});
// Example usage: Start the server
// app.listen(3001, () => console.log('API server running on port 3001'));
How it works: This Node.js (Express) snippet demonstrates how to configure CORS using the `cors` middleware to restrict access to specific origins. The `allowedOrigins` array lists the domains permitted to make cross-origin requests. The `origin` function within `corsOptions` dynamically checks if the incoming request's origin is in the allowed list. If not, access is denied. `methods` specifies allowed HTTP methods, and `credentials: true` allows sending cookies or authorization headers, which is important for authenticated requests. This setup prevents unauthorized domains from interacting with your API.