Search code examples
node.jsexpresscors

How to set subdomain rules for CORS in express.js?


I have a Web application with the front end as a React.js app, and the back end as a Node.js app using express.js. I intend to use as little money as possible for deploying these as this is for a personal project, so I am using Netlify for hosting the front end (free) and Heroku for hosting the back end ($0.010/hr).

My current setup for the front end on Netlify supports per-branch deployment on different URLs with the branch as a prefix like so: feature123 deployed on myurl.netlify.com will be deployed as feature123--myurl.netlify.com.

I need money per back-end deployment, so I don't want to spin up new back-end instances per branch. Instead, I want to deploy only one back-end and have all my front-end instances (variations per branch) use the same back-end instance.

The issue: I have to set up CORS for my back-end and I want to avoid adding CORS rules for each branch on the front-end. What I am looking for is a rule something like *myurl.netlify.com, which covers any source coming from my source. How do I achieve this?


Solution

  • With help cors library you can achieve this by passing Regexp or Array of string/Regexp to origin option as mentioned here.

    An example could be like this

    cors({
      origin: [
        'https://myurl.netlify.app', 
        /^https:\/\/[0-9A-Za-z]+--myurl\.netlify\.app$/
      ],
      // ....
    })