JAVASCRIPT

Configure Secure CORS in Node.js Express Applications

Implement secure Cross-Origin Resource Sharing (CORS) in your Node.js Express API using the `cors` middleware, specifying allowed origins, methods, and headers to protect your resources.

// Install the cors package: npm install cors

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

// Basic CORS configuration (allows all origins - NOT recommended for production APIs)
// app.use(cors());

// --- Recommended: Specific CORS configuration for production ---
const allowedOrigins = [
    'https://yourfrontenddomain.com',
    'http://localhost:8080' // For local development only
];

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: 204 // Some legacy browsers (IE11, various SmartTVs) choke on 200
};

// Apply the CORS middleware with specific options
app.use(cors(corsOptions));

// Middleware to parse JSON request bodies
app.use(express.json());

// Example API route
app.get('/api/data', (req, res) => {
    res.json({ message: 'This is secure data from the API!' });
});

app.post('/api/submit', (req, res) => {
    // console.log('Received data:', req.body);
    res.status(200).json({ status: 'success', received: req.body });
});

app.listen(port, () => {
    // console.log(`Server listening at http://localhost:${port}`);
});
How it works: This Node.js Express snippet demonstrates how to securely configure Cross-Origin Resource Sharing (CORS). Instead of using a default configuration that allows all origins (which is insecure for production), it defines a whitelist of `allowedOrigins`. The `corsOptions` object specifies which origins, HTTP methods, and headers are permitted, ensuring that only trusted client applications can interact with your API. The `credentials: true` flag is important when your API needs to handle cookies or authorization headers for cross-origin requests.

Need help integrating this into your project?

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

Hire DigitalCodeLabs