JAVASCRIPT
Implementing Robust CORS Policy in Express.js
Configure a secure and fine-grained Cross-Origin Resource Sharing (CORS) policy in Express.js to control access from trusted origins, headers, and methods.
const express = require('express');
const cors = require('cors'); // npm install cors
const app = express();
const port = 3000;
// Define a list of allowed origins.
// In production, these should be specific domains, not wildcards.
const allowedOrigins = [
'http://localhost:8080', // Example frontend development server
'https://my-frontend-app.com', // Example production frontend
'https://another-trusted-domain.org'
];
const corsOptions = {
origin: function (origin, callback) {
// Allow requests with no origin (like mobile apps or curl requests)
// or if the origin is in our allowed list.
if (!origin || allowedOrigins.indexOf(origin) !== -1) {
callback(null, true);
} else {
callback(new Error('Not allowed by CORS'));
}
},
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE', // Allowed HTTP methods
allowedHeaders: 'Content-Type,Authorization,X-Requested-With,Accept,Origin', // Allowed request headers
credentials: true, // Allow sending cookies/auth headers from origin
optionsSuccessStatus: 204 // Some legacy browsers (IE11, various SmartTVs) choke on 200
};
// Apply the CORS middleware with the defined options
app.use(cors(corsOptions));
// Middleware to parse JSON request bodies
app.use(express.json());
// A simple protected route
app.get('/api/data', (req, res) => {
res.json({ message: 'This is protected data from the API!' });
});
// A route that requires specific methods
app.post('/api/submit', (req, res) => {
console.log('Received data:', req.body);
res.status(200).json({ status: 'success', data: req.body });
});
app.listen(port, () => {
console.log(`Server listening at http://localhost:${port}`);
});
How it works: Cross-Origin Resource Sharing (CORS) is a security mechanism that allows web browsers to make requests to a different domain than the one the web page originated from. This Express.js snippet demonstrates a robust CORS configuration using the `cors` middleware. Instead of a simple wildcard, it uses a dynamic `origin` function to validate incoming requests against a whitelist of `allowedOrigins`. It also explicitly defines allowed HTTP `methods`, `allowedHeaders`, and sets `credentials: true` to enable cookie-based authentication, ensuring only trusted frontend applications can interact with the API.