I am trying to set the URL dynamically in .env file depending on my working branch. Is it possible to use If Else statement inside .env file? I also would like to read the ENV variable from the windows environment variables.
Anyways, I am working with a react app. Here is What I have tried but didn't work:
ENV = 'develop'
REACT_APP_BASE_URL = ''
if(ENV == 'develop'){
REACT_APP_BASE_URL = 'https://api.dev.myurl.com'
}else if(ENV == 'staging'){
REACT_APP_BASE_URL = 'https://api.staging.myurl.com'
}else if(ENV == 'production'){
REACT_APP_BASE_URL = 'https://api.pro.myurl.com'
}
Нi Dev. Rafiq,
I personally resort to utility functions for that purpose.
Example, /utils/url.ts:
export const isProduction = process.env.NODE_ENV === 'production'
export const isDevelopment = process.env.NODE_ENV === 'development'
export const isStaging = process.env.NODE_ENV === 'staging'
export const websiteUrl = isProduction
? 'https://api.pro.myurl.com'
: isDevelopment
? 'https://api.dev.myurl.com'
: 'https://api.staging.myurl.com'
Instead of using the REACT_APP_BASE_URL environment variable, you could simply use websiteURL.
You might benefit from making these variables exportable elsewhere.
Example: If you'd wish to render a particular element only in staging then you could reuse isStaging as such — isStaging && <MyElement/>.
This approach could also be beneficial when scaling up your application, typically to use different API keys for different purposes like, Google Analytics, reCAPTCHA...etc Since it's not recommended to mix production data with staging.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With