JAVASCRIPT

Configure Secure CORS for Express.js APIs

Learn to securely configure Cross-Origin Resource Sharing (CORS) in your Express.js API, controlling which domains can access your resources and preventing unauthorized cross-origin requests.

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

// Define allowed origins for production
const allowedOrigins = [
    'https://your-frontend-domain.com',
    'https://another-approved-domain.com',
    // 'http://localhost:3000' // For development, remove in production or use environment variable
];

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', // Allowed HTTP methods
    credentials: true, // Allow cookies to be sent
    optionsSuccessStatus: 200 // Some legacy browsers (IE11, various SmartTVs) choke on 204
};

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

// Example route
app.get('/api/data', (req, res) => {
    res.json({ message: 'Data from secured API' });
});

// Other routes
app.get('/', (req, res) => {
    res.send('Welcome to the API!');
});

// const PORT = process.env.PORT || 3001;
// app.listen(PORT, () => {
//     console.log(`CORS-enabled web server listening on port ${PORT}`);
// });
How it works: This JavaScript snippet demonstrates how to implement secure Cross-Origin Resource Sharing (CORS) in an Express.js API using the `cors` middleware. Instead of simply allowing all origins, it defines a whitelist of `allowedOrigins` to restrict access to only trusted frontend applications. The `corsOptions` object configures which HTTP methods are permitted and enables `credentials` to allow cookies to be sent across origins, which is crucial for authenticated sessions. This approach prevents unauthorized domains from making requests to your API, significantly enhancing the security of your web application.

Need help integrating this into your project?

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

Hire DigitalCodeLabs