JAVASCRIPT
Securely Configure CORS for REST APIs in Express.js
Learn to implement a secure Cross-Origin Resource Sharing (CORS) policy in your Express.js API to control access from different origins and protect your resources effectively.
const express = require('express');
const cors = require('cors'); // CORS middleware for Express
const app = express();
// Middleware to parse JSON request bodies
app.use(express.json());
// --- SECURE CORS CONFIGURATION ---
// Option 1: Allow specific origins (most secure for production)
const allowedOrigins = [
'http://localhost:3001', // Example for development frontend
'https://your-frontend-domain.com' // Your actual production frontend domain
];
const corsOptions = {
origin: (origin, callback) => {
// Allow requests with no origin (like mobile apps or curl requests)
// and requests from allowedOrigins
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
credentials: true, // Allow cookies to be sent with cross-origin requests
optionsSuccessStatus: 200 // Some legacy browsers (IE11, various SmartTVs) choke on 204
};
app.use(cors(corsOptions));
// Option 2: Basic, less secure (for quick development or public APIs without sensitive data)
// app.use(cors()); // Allows ALL origins (*) - generally NOT recommended for private APIs
// Option 3: Allow a single specific origin
// app.use(cors({ origin: 'https://your-frontend-domain.com' }));
// --- Example API Routes ---
app.get('/api/data', (req, res) => {
res.json({ message: 'This is some secure data from the API!' });
});
app.post('/api/submit', (req, res) => {
console.log('Received data:', req.body);
res.json({ message: 'Data submitted securely', received: req.body });
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`API server running on port ${PORT}`);
});
How it works: This snippet demonstrates how to securely configure Cross-Origin Resource Sharing (CORS) in an Express.js API using the `cors` middleware. The most secure approach involves defining a whitelist of `allowedOrigins` to restrict which domains can make cross-origin requests, preventing unauthorized access to your API resources. It also configures allowed HTTP methods (`methods`) and enables `credentials` if cookies or authorization headers need to be sent cross-origin, ensuring tight control over your API's accessibility.