JAVASCRIPT

Configuring Secure CORS for API Access

Set up Cross-Origin Resource Sharing (CORS) correctly in your Node.js Express application to control which origins can access your API, enhancing security and preventing unauthorized cross-domain requests.

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

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

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
};

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

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

app.post('/api/submit', (req, res) => {
    res.status(200).json({ message: 'Data submitted securely!' });
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));

// To run this:
// 1. npm init -y
// 2. npm install express cors
// 3. Save as app.js and run node app.js
// Test with:
// Try accessing from allowed origin in a browser.
// Try curl from a different origin, or modify `origin` header.
How it works: This Node.js Express snippet demonstrates how to securely configure Cross-Origin Resource Sharing (CORS) using the `cors` middleware. Instead of simply allowing all origins (`cors()`), it sets up a dynamic `origin` function within `corsOptions` to explicitly whitelist a predefined list of `allowedOrigins`. This ensures that only trusted frontend applications or clients can make requests to your API, preventing unauthorized domains from interacting with your backend resources. It also configures allowed HTTP methods and `credentials: true` to enable cookie-based authentication across origins, and sets `optionsSuccessStatus` for broader browser compatibility. Proper CORS configuration is a fundamental security practice for web APIs.

Need help integrating this into your project?

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

Hire DigitalCodeLabs