JAVASCRIPT
Dynamic CORS Policy for Express.js APIs
Implement a flexible CORS policy in your Express.js API, allowing dynamic configuration of allowed origins based on environment or specific requirements.
const express = require('express');
const cors = require('cors'); // Official CORS middleware for Express
const app = express();
// IMPORTANT: Configure allowed origins dynamically based on your environment
const allowedOrigins = [
'http://localhost:3000', // Development frontend
'http://localhost:8080', // Another development frontend
'https://your-production-app.com', // Production frontend
// Add more origins as needed
];
// CORS configuration options
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', 'POST', 'PUT', 'DELETE', 'OPTIONS'], // Allowed HTTP methods
allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With'], // Allowed request headers
credentials: true, // Allow sending of cookies and authorization headers
optionsSuccessStatus: 200 // Some legacy browsers (IE11, various SmartTVs) choke on 204
};
// Apply CORS middleware
app.use(cors(corsOptions));
// Simple route
app.get('/', (req, res) => {
res.send('Hello from your CORS-enabled API!');
});
// Example protected route
app.get('/data', (req, res) => {
// In a real app, you'd verify JWT/session here
res.json({ message: 'This is some protected data!' });
});
// Error handling middleware (optional but good practice)
app.use((err, req, res, next) => {
if (err.message === 'Not allowed by CORS') {
return res.status(403).json({ error: err.message });
}
console.error(err.stack);
res.status(500).send('Something broke!');
});
const PORT = process.env.PORT || 3001;
app.listen(PORT, () => {
console.log(`CORS-enabled API listening on port ${PORT}`);
console.log(`Allowed origins: ${allowedOrigins.join(', ')}`);
});
How it works: This Node.js snippet demonstrates how to implement a dynamic Cross-Origin Resource Sharing (CORS) policy for an Express.js API using the `cors` middleware. Instead of a static wildcard (`*`), it defines a list of `allowedOrigins` and uses a custom `origin` function within `corsOptions`. This function checks if the incoming request's origin is either not present (e.g., direct API calls, mobile apps) or matches one of the explicitly allowed origins, thereby providing a flexible yet secure way to control which client-side applications can access your API. It also configures allowed methods, headers, and credential handling for robust cross-origin communication.