JAVASCRIPT

Secure Cross-Origin Resource Sharing (CORS) in Express

Learn to securely configure Cross-Origin Resource Sharing (CORS) in a Node.js Express application, controlling which origins can access your server's resources.

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

const app = express();

// Define a whitelist of allowed origins
const allowedOrigins = [
  'https://www.myfrontend.com',
  'https://another.trusted.domain',
  'http://localhost:8080' // For development
];

// Configure CORS options
const corsOptions = {
  origin: function (origin, callback) {
    // Allow requests with no origin (like mobile apps or curl requests)
    // or if the origin is in our whitelist.
    if (!origin || allowedOrigins.indexOf(origin) !== -1) {
      callback(null, true);
    } else {
      callback(new Error('Not allowed by CORS'));
    }
  },
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], // Allowed HTTP methods
  allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With'], // Allowed request headers
  credentials: true, // Allow cookies to be sent with cross-origin requests
  maxAge: 3600 // How long the results of a preflight request can be cached
};

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

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

// Another example route that allows all origins (use with extreme caution!)
app.get('/public-data', cors(), (req, res) => {
    res.json({ message: 'This data is publicly accessible from any origin.' });
});


const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});
How it works: This snippet demonstrates how to implement secure Cross-Origin Resource Sharing (CORS) in an Express.js application using the `cors` middleware. By defining an `allowedOrigins` whitelist and a custom `origin` function, the server strictly controls which domains are permitted to make cross-origin requests. This prevents unauthorized websites from accessing your API or resources, mitigating data leakage and other security risks. The configuration also specifies allowed HTTP methods, headers, and enables credential exchange, providing fine-grained control over cross-origin interactions.

Need help integrating this into your project?

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

Hire DigitalCodeLabs