JAVASCRIPT

Secure Server-Side CORS Configuration in Node.js Express

Properly configure Cross-Origin Resource Sharing (CORS) in your Node.js Express application to control which domains can safely access your API resources.

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

const app = express();

const allowedOrigins = ['http://localhost:3000', 'https://yourfrontend.com'];

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

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

// Your routes go here
app.get('/', (req, res) => {
  res.send('Hello Secure CORS!');
});

app.listen(3001, () => {
  console.log('Server running on port 3001');
});
How it works: This Node.js Express snippet demonstrates a secure way to configure Cross-Origin Resource Sharing (CORS) using the `cors` middleware. Instead of simply allowing all origins (`cors()`), it defines a whitelist of `allowedOrigins`. The `origin` function dynamically checks if the incoming request's origin is in the allowed list, rejecting unauthorized requests. It also configures `methods` and `credentials` to explicitly control what types of requests and header inclusions are permitted from allowed origins, enhancing the security posture against unwanted cross-origin access.

Need help integrating this into your project?

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

Hire DigitalCodeLabs