← Back to all snippets
JAVASCRIPT

Secure CORS Configuration in Express.js

Implement robust Cross-Origin Resource Sharing (CORS) policies in your Express.js application to control which origins can access your API resources securely.

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

// Whitelist allowed origins
const allowedOrigins = [
    'http://localhost:3000', // Example: your frontend development server
    'https://your-production-frontend.com' // Example: your production frontend domain
];

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

// Apply CORS middleware
app.use(cors(corsOptions));

// Your API routes
app.get('/data', (req, res) => {
    res.json({ message: 'This is secure data!' });
});

const PORT = process.env.PORT || 3001;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
How it works: This snippet demonstrates how to configure CORS (Cross-Origin Resource Sharing) in an Express.js application using the `cors` middleware. It defines a whitelist of `allowedOrigins`, ensuring that only specified frontend domains can make requests to the API. The `corsOptions` object provides fine-grained control over accepted methods, credentials handling (for cookies), and success status codes, preventing unauthorized 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