NodeJS Parseing RegEx from environmental variable


I am using the node package cors, and I’d like to pass regular expressions into the allowed origins. Still, since I am hosting my node application on multiple servers for "production" and "staging", I am using environmental variables to store the origins. Still, when env variables are parsed they get returned as strings.

Here is an example of my env variable


this means I want only origins that have both "" and "" to work, according to so express documentation, so I parse the env variable as follows

export const CORS_ORIGINS = process.env.CORS_ORIGINS?.split(',')

but what is being set in the cors origins is ["/\.example\.com$/", "/\.example\.app$/"]
how do I make it this [/\.example\.com$/, /\.example\.app$/] instead.


You can use RegExp constructor to create a RegExp from strings.
In this case, you will need to modify the environment variables a bit


then in your code

export const CORS_ORIGINS = process.env.CORS_ORIGINS?.split(',').map(item => new RegExp(item));

Answered By – Đăng Khoa Đinh

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published