JAVASCRIPT

Securely Configure CORS in Node.js Express Application

Implement robust Cross-Origin Resource Sharing (CORS) policies in your Express.js app to restrict access to allowed origins and methods, preventing unauthorized cross-origin requests.

const express = require('express');
const cors = require('cors'); // Import the CORS middleware

const app = express();
const port = 3000;

// Define allowed origins
const allowedOrigins = [
  'http://localhost:8080', // Example for a local frontend app
  'https://your-frontend-domain.com' // Example for a deployed frontend
];

// CORS options configuration
const corsOptions = {
  origin: function (origin, callback) {
    // Allow requests with no origin (like mobile apps or curl requests)
    // Or if the origin is in our allowed list
    if (!origin || allowedOrigins.indexOf(origin) !== -1) {
      callback(null, true);
    } else {
      callback(new Error('Not allowed by CORS'));
    }
  },
  methods: ['GET', 'POST', 'PUT', 'DELETE'], // Specify allowed HTTP methods
  allowedHeaders: ['Content-Type', 'Authorization'], // Specify allowed request headers
  credentials: true, // Allow sending cookies and HTTP authentication credentials
  optionsSuccessStatus: 200 // Some legacy browsers (IE11, various SmartTVs) choke on 204
};

// Apply CORS middleware globally or to specific routes
app.use(cors(corsOptions));

// Example routes
app.get('/data', (req, res) => {
  res.json({ message: 'This is protected data.' });
});

app.post('/submit', (req, res) => {
  res.json({ status: 'success', received: req.body });
});

// Handle preflight requests for non-simple requests
// The `cors` middleware handles this automatically when `cors(corsOptions)` is used

app.listen(port, () => {
  console.log(`Server listening at http://localhost:${port}`);
  console.log('Test with a frontend from an allowed origin (e.g., http://localhost:8080)');
  console.log('Requests from other origins will be blocked by CORS.');
});
How it works: This snippet demonstrates how to securely configure Cross-Origin Resource Sharing (CORS) in a Node.js Express application using the `cors` middleware. Instead of using `cors()` which allows all origins, it defines a whitelist of `allowedOrigins` and checks incoming requests against this list. It also explicitly sets `methods` and `allowedHeaders` to limit what cross-origin requests can do. This controlled approach prevents unauthorized domains from accessing your API resources, significantly reducing potential security risks like data leakage or malicious scripting.

Need help integrating this into your project?

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

Hire DigitalCodeLabs