← Back to all snippets
JAVASCRIPT

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

Implement secure CORS policies in Node.js Express applications, allowing necessary cross-origin requests while preventing unauthorized access to your server resources.

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

const app = express();

// Whitelist specific origins for CORS
const allowedOrigins = [
  'http://localhost:3000', // Your frontend development server
  'https://your-production-frontend.com', // Your production frontend
  'https://another-trusted-domain.net'
];

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', 'POST', 'PUT', 'DELETE'], // Specify allowed HTTP methods
  allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With'], // Specify allowed headers
  credentials: true // Allow cookies/authorization headers to be sent
};

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

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

const PORT = process.env.PORT || 3001;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});
How it works: This Node.js Express snippet demonstrates how to securely configure Cross-Origin Resource Sharing (CORS). Instead of using a wildcard `*` (which is highly insecure for production), it defines a `whitelist` of `allowedOrigins`. The `cors` middleware is configured with a function for `origin` to dynamically check if the incoming request's origin is in the allowed list. It also explicitly specifies `methods` and `allowedHeaders` that clients are permitted to use, and `credentials: true` if your application needs to handle cookies or authorization headers across origins. This fine-grained control prevents unauthorized domains from making requests to your API, mitigating risks like data theft and CSRF.

Need help integrating this into your project?

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

Hire DigitalCodeLabs