JAVASCRIPT

Secure Cross-Origin Resource Sharing (CORS) Configuration

Configure Express.js to securely handle Cross-Origin Resource Sharing (CORS) by specifying allowed origins, methods, and headers, enhancing API security.

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

const app = express();

// Whitelist of allowed origins (e.g., your frontend app's URL)
const allowedOrigins = [
  'https://www.yourfrontend.com',
  'http://localhost:3000' // For development
];

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

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

const PORT = process.env.PORT || 3001;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});
How it works: This snippet demonstrates how to securely configure CORS in an Express.js application. Instead of allowing all origins (`origin: '*'`), it uses a dynamic function to whitelist specific frontend domains, preventing unauthorized domains from accessing your API. It also defines allowed HTTP methods and enables credentials, which is crucial for sending cookies or authorization headers securely across origins. This prevents Cross-Site Scripting (XSS) attacks that exploit overly permissive CORS policies.

Need help integrating this into your project?

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

Hire DigitalCodeLabs