Enable CORS for all requests from a certain domain in Express.js/Node.js application?

Answered
nick asked this question 1 year, 5 months ago
nick on Jan 4, 2022 · Edited

In my Express.js/Node.js application, how can I enable CORS request from any URLs from a given domain name?

My current CORS configuration:

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

I'm using the cors NPM package to configure CORS settings for my application.

2 suggested answers
itsbambi on Jan 12, 2022

Update your origin setting to this:

cors({
  origin: /domain\.com$/
})

This would configure your Access-Control-Allow-Origin CORS header for any request with the domain.com domain.

So, requests from api.domain.com, assets.domain.com, etc. would work.

0 replies
yaboy01 on Jan 12, 2022

You can use a regular expression:

origin: /my_domain\.com$/

Or you can also create an array of accepted URLs:

origin: ["https://my_url.com", "https://my_url_2.com", "https://my_url_3.com"]
0 replies
Answered