JAVASCRIPT

Configure Secure Cross-Origin Resource Sharing (CORS) in Node.js Express

Learn to securely configure CORS in your Node.js Express application to control which origins can access your resources, preventing unauthorized cross-origin requests.

const express = require('express');
const cors = require('cors'); // npm install cors
const app = express();
const port = 3000;

// IMPORTANT: In a production environment, allowed origins should be loaded from environment variables
// and configured meticulously. Never allow '*' unless absolutely necessary and understood.
const allowedOrigins = [
    'http://localhost:8080', // Example: your development frontend
    'https://your-production-frontend.com', // Example: your production frontend
    'https://another-trusted-domain.com'
];

// Option 1: Basic CORS with specific origin checking
// This is more secure than simply `app.use(cors())`
app.use(cors({
    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: ${origin}`;
            return callback(new Error(msg), false);
        }
        return callback(null, true);
    },
    methods: ['GET', 'POST', 'PUT', 'DELETE'], // Specify allowed HTTP methods
    credentials: true, // Allow cookies to be sent
    optionsSuccessStatus: 200 // Some legacy browsers (IE11, various SmartTVs) choke on 204
}));

// Option 2: More advanced CORS configuration for specific routes (if needed)
// app.get('/api/public', cors(), (req, res) => {
//     res.json({ message: 'This is a public API endpoint, open to all origins with default CORS.' });
// });

// app.post('/api/secure', cors({ origin: 'https://only-my-trusted-app.com' }), (req, res) => {
//     res.json({ message: 'This is a secure API endpoint for a specific origin.' });
// });


// A simple protected route
app.get('/api/data', (req, res) => {
    res.json({ message: 'This data is protected by the global CORS policy.' });
});

app.listen(port, () => {
    console.log(`Server listening at http://localhost:${port}`);
    console.log('Try accessing /api/data from allowed origins.');
    console.log('For example, a frontend running at http://localhost:8080');
    console.log('Requests from other origins will be blocked by CORS policy.');
});

// To test:
// 1. Start this Node.js server.
// 2. Open your browser console and try:
//    fetch('http://localhost:3000/api/data') // Works from same origin, or allowedOrigins if it's your current domain
// 3. Or, open a simple HTML file from a different domain (e.g., file:/// or another port) with:
//    fetch('http://localhost:3000/api/data')
//    .then(res => res.json())
//    .then(data => console.log(data))
//    .catch(err => console.error(err));
//    You should see a CORS error in the browser console if the origin is not allowed.
How it works: This Node.js Express snippet demonstrates how to implement a secure Cross-Origin Resource Sharing (CORS) policy. Instead of using a wildcard `*` (which is highly insecure for authenticated resources), it configures a dynamic `origin` function. This function checks if the requesting origin is in a predefined list of `allowedOrigins`. It also explicitly defines `methods` and `credentials` to provide granular control over cross-origin interactions, mitigating risks of unauthorized data access or manipulation.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs