← Back to all snippets
JAVASCRIPT

Securely Configure CORS Policy for Web APIs

Learn to implement a secure Cross-Origin Resource Sharing (CORS) policy in your Node.js Express application to control access to your API endpoints effectively.

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

// Define a whitelist of allowed origins
const allowedOrigins = [
  'https://yourfrontend.com',
  'https://anotheralloweddomain.com',
  'http://localhost:3000' // For development
];

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,HEAD,PUT,PATCH,POST,DELETE',
  credentials: true, // Allow cookies to be sent with requests
  optionsSuccessStatus: 204 // Some legacy browsers (IE11, various SmartTVs) choke on 200
};

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

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

const PORT = process.env.PORT || 4000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});
How it works: This snippet demonstrates how to configure a secure Cross-Origin Resource Sharing (CORS) policy in an Express.js application using the `cors` middleware. It sets up a whitelist of allowed origins, ensuring that only trusted client applications can make requests to your API. The `corsOptions` object also specifies allowed HTTP methods and enables credentials (like cookies) for cross-origin requests, enhancing both security and functionality.

Need help integrating this into your project?

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

Hire DigitalCodeLabs