Setting Up CORS in Express.js

What is CORS?

Cross-Origin Resource Sharing (CORS) is a security feature implemented by browsers to prevent unauthorized access to resources on another domain. It controls how web pages from different origins (domains) can request resources from your server.

Why Set Up CORS?

In a typical setup, your front end might be hosted on https://frontend-domain.com, while your API runs on https://api-domain.com. By default, browsers block requests from one domain to another unless explicitly allowed. CORS headers help configure this behavior by allowing certain origins to access your API.

Installing CORS Middleware

In Express.js, you can use the cors (opens in a new tab) middleware, which simplifies the configuration process.

Step 1: Install the CORS Package

npm install cors

Setting Up CORS in Express.js

What is CORS?

Cross-Origin Resource Sharing (CORS) is a security feature implemented by browsers to prevent unauthorized access to resources on another domain. It controls how web pages from different origins (domains) can request resources from your server.

Why Set Up CORS?

In a typical setup, your front end might be hosted on https://frontend-domain.com, while your API runs on https://api-domain.com. By default, browsers block requests from one domain to another unless explicitly allowed. CORS headers help configure this behavior by allowing certain origins to access your API.

Installing CORS Middleware

In Express.js, you can use the cors (opens in a new tab) middleware, which simplifies the configuration process.

Step 1: Install the CORS Package

npm install cors

Step 2: Basic Configuration

To enable CORS with default settings, you can add the middleware in your Express app. This will allow requests from any origin.

 
// app.js or index.js
 
const express = require('express');
const cors = require('cors');
 
const app = express();
 
// Enable CORS for all routes and origins
app.use(cors());
 
// Sample route
app.get('/api/data', (req, res) => {
  res.json({ message: 'CORS-enabled API' });
});
 
app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});

Step 3: Allow Specific Origins

For security, it's often best to restrict access to specific origins. You can configure this by passing an options object to cors().

const corsOptions = {
  origin: 'https://trusted-domain.com', // Allow only this origin
  methods: ['GET', 'POST'],             // Allow specific HTTP methods
  credentials: true                     // Allow cookies or other credentials
};
 
app.use(cors(corsOptions));
 

Step 4: Dynamic CORS Configuration You may need to allow different origins based on specific conditions, such as the request origin.

const dynamicCorsOptions = (req, callback) => {
  const allowedOrigins = ['https://trusted-domain.com', 'https://another-trusted.com'];
  const origin = req.header('Origin');
 
  if (allowedOrigins.includes(origin)) {
    callback(null, { origin: true });
  } else {
    callback(new Error('Not allowed by CORS'));
  }
};
 
app.use(cors(dynamicCorsOptions));

Step 5: CORS for Specific Routes Only

To limit CORS to certain routes, you can add it as middleware only on those routes:

app.get('/public-data', cors(), (req, res) => {
  res.json({ message: 'This route is CORS-enabled' });
});
 
app.post('/private-data', (req, res) => {
  res.json({ message: 'This route is not CORS-enabled' });
});

Advanced Configuration Options You can further customize CORS with additional options:

allowedHeaders: Specifies which headers are allowed in the request. For example:

allowedHeaders: ['Content-Type', 'Authorization']
exposedHeaders: Specifies headers that the browser is allowed to access from the response. For example:
exposedHeaders: ['Content-Length', 'X-Kuma-Revision']
maxAge: Defines how long the results of a preflight request can be cached (in seconds). For example:
maxAge: 600

Best Practices

Restrict Origins: Only allow trusted domains instead of using the wildcard *. This reduces the risk of unwanted domains accessing your API. Limit HTTP Methods: Restrict CORS to only the methods your API supports, e.g., GET, POST, and PUT. Secure Sensitive Routes: Use CORS only where necessary. For sensitive routes, you might need to implement additional security measures beyond CORS. Use HTTPS: Always enable HTTPS for secure communication between client and server, especially when dealing with sensitive data. Test CORS Configuration: Use browser developer tools or tools like Postman to test your CORS settings and ensure that they work as expected.