Allow more than one CORS origin URL in a Express.js/Node.js application?

suparman21 asked this question 21 days ago
suparman21 21 days ago

In my Node.js/Express.js application, I have CORS enabled for the URL of my frontend website.

My CORS configuration code looks like this right now:

app.use(cors({origin: "}))

How do I add more than one URL in the CORS settings?

3 suggested answers
1 reply
nick 13 days ago · Edited

In the cors NPM package, you can pass the cors object an array of URLs for the origin option:

origin: ["", "", "", ""]

That will allow CORS for all four of those URLs in this example.

0 replies
looper003 13 days ago · Edited

You can create a whitelist array like this:

var whitelist = ["", ""]

var corsOptions = {
  origin: function (origin, callback) {
    if (whitelist.indexOf(origin) !== -1) {
      callback(null, true)
    } else {
      callback(new Error("Not allowed by CORS"))

This will allow CORS for both of the URLs in the whitelist array.

This is an example they give in their documentation.

1 reply
suparman21 13 days ago

This worked, thanks so much!

yaboy01 13 days ago

You can use a regular expression for the origin option:

origin: /domain\.com$/

This will allow CORS from all URLs with the domain.

0 replies