NodeJS Parseing RegEx from environmental variable

Issue

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

CORS_ORIGINS=/\.example\.com$/,/\.example\.app$/

this means I want only origins that have both "example.com" and "example.app" 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.

Solution

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

CORS_ORIGINS=\\.example\\.com$,\\.example\\.app$

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