Usage of env variables inside React
Environment variables are used in application to store configuration settings and other data. It is used to separate configuration from source code making it easier to manage different environments, such as development, testing, production, without changing the code.
Usage of environment variables through env file
The environments variables are embedded during the build time. They exists within process.env files. During the build process, environment variables used inside the application are replaced by their corresponding value from .env file.
The environment variables shouldn’t contain any sensitive information like api keys or secrets. As they are embedded into JavaScript code anyone can inspect the env variables from the source code. So proper precaution should be taken while storing some value inside the env variable.
To use env variables inside react app, we can declare env variables inside .env file with a prefix 'REACT_APP'
REACT_APP_DUMMY_VALUE="value of env variable"
We can access the env variable using process.env inside the files.
function Component() {
const envVar = process.env.REACT_APP_DUMMY_VALUE
// ... rest of the code
}
To use env variables with custom webpack files we need 'dotenv-webpack' plugin.
module.exports = {
// ... configurations
plugins: [
// ... other plugins
new Dotenv()
],
// ... rest of the configurations
}
Usage of environment variable by detecting the environment from the url
Instead of using env variables we can also use config files where we can set configuration values of different environments based upon url. In this way can eliminate the need for env variables. This is the preferred approach when we need to use configuration variables on runtime in the CSR apps. It can be implemented in below way.
<!-- config.js -->
const config = {
DEV: {
'app_variable1': 'some value for dev mode',
'app_variable2': 'Other value for dev mode'
},
PROD: {
'app_variable1': 'some value for prod mode',
'app_variable2': 'Other value for prod mode'
}
}
Create a utility function to get the the current environment from url.
export const getCurrentEnv = () => {
const hostname = window.location.hostname
const environmentPrefix = hostname.split('-')[0].toLocaleLowerCase()
if(environmentPrefix.startsWith('it')) {
return 'IT'
} else if(environmentPrefix.startsWith('uat')) {
return 'UAT'
} else if(environmentPrefix.startsWith('dev')) {
return 'DEV'
} else {
return 'PROD'
}
}
In the application use the utility function to retrieve the environment and use the corresponding value of the env variable.
const mode = getCurrentEnv()
const envValue = config[mode]
A poc of url based environment detection and using respective environment variable approach is added in the repo https://github.com/Paul-Ayanava/csr-env-conevtion-over-configuration