JAVASCRIPT

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

Learn to properly configure CORS in your Node.js Express API, allowing secure communication only from trusted origins while preventing unauthorized cross-origin requests.

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

// Define allowed origins
const allowedOrigins = [
    'https://your-frontend-domain.com',
    'http://localhost:8080' // For development
];

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

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

// Example API route
app.get('/api/data', (req, res) => {
    // This endpoint will only be accessible from 'https://your-frontend-domain.com'
    // or 'http://localhost:8080' if accessed via a browser
    res.json({ message: 'Secure data from your API!' });
});

app.listen(port, () => {
    console.log(`API server running with CORS configured at http://localhost:${port}`);
});

// --- IMPORTANT SECURITY NOTE ---
// NEVER use app.use(cors()); without specific origin restrictions in production.
// This allows ALL origins, opening your API to potential security risks.
How it works: This Node.js Express snippet demonstrates how to securely implement Cross-Origin Resource Sharing (CORS). Instead of blindly allowing all origins, it configures the `cors` middleware to only permit requests from a predefined list of trusted domains. This protects your API from unauthorized access from malicious websites, ensuring that your backend resources are only consumed by your intended frontend applications, significantly enhancing API security.

Need help integrating this into your project?

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

Hire DigitalCodeLabs