ArticleZip > Allow Multiple Cors Domain In Express Js

Allow Multiple Cors Domain In Express Js

When you're working with web applications and APIs, you may encounter the need to allow multiple Cross-Origin Resource Sharing (CORS) domains in your Express.js server. CORS is an important security feature that restricts resource access from different origins. However, there are times when you want to permit cross-origin requests from multiple domains in your Express.js application. Here's how you can achieve this in a few simple steps:

1. **Install the CORS Module**:
The first step is to install the `cors` module, if you haven't already. You can do this using npm by running the following command in your project directory:

Bash

npm install cors

2. **Configure CORS in Your Express.js Server**:
Next, you need to configure CORS in your Express.js server. You can do this by requiring the `cors` module and using it as middleware in your application. Here's how you can set up CORS to allow requests from multiple domains:

Javascript

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

const app = express();

const allowedDomains = ['http://domain1.com', 'http://domain2.com'];

const corsOptions = {
  origin: (origin, callback) => {
    if(allowedDomains.indexOf(origin) !== -1 || !origin) {
      callback(null, true);
    } else {
      callback(new Error('Not allowed by CORS'));
    }
  }
};

app.use(cors(corsOptions));

// Define your routes here

app.listen(3000, () => {
  console.log('Server running on port 3000');
});

In the code snippet above, we are defining an array `allowedDomains` that contains the list of domains from which we want to allow CORS requests. We then set up `corsOptions` with a custom function that checks if the requesting origin is in the `allowedDomains` array. If it is, the request is allowed; otherwise, an error is returned.

3. **Handle Preflight Requests**:
When dealing with CORS, it's essential to handle preflight requests for certain types of requests. Preflight requests are options requests that the browser automatically sends in some cross-origin resource sharing scenarios. To handle preflight requests in Express.js, you can add the following code to your server setup:

Javascript

app.options('*', cors(corsOptions));

The above code snippet sets up a preflight request handler for all routes in your Express.js application.

4. **Testing Your CORS Configuration**:
After setting up CORS with multiple domain support in your Express.js server, it's crucial to test your configuration thoroughly. You can use tools like Postman or your browser's developer tools to simulate cross-origin requests from different domains and ensure that your server handles them correctly.

By following these simple steps, you can allow multiple CORS domains in your Express.js application, enabling cross-origin resource sharing from specific domains while maintaining the security of your web server.