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

suparman21 asked this question 1 year, 5 months ago
suparman21 on Jan 4, 2022

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 on Jan 12, 2022 · 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 on Jan 12, 2022 · 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 on Jan 12, 2022

This worked, thanks so much!

yaboy01 on Jan 12, 2022

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