DEV Community

Ismail PE
Ismail PE

Posted on

Handling environment variable: React and AWS Cognito

This post is for beginners. You can use the same code base for all environments if you have clearly handled the environment specific changes. Those changes should be minimised like the api urls. I have described the process in four steps.

First, I have created separate files where these differences are defined. For example, my files are named config.prod, config.qa and config.dev. And the contents of file is like
export default {
api: {
baseURL: “https://..”,
fetchUsers: “https://..”,
}
cognito: {
USER_POOL_ID: 1234,
}
}
Prod config file will have prod api url domain and dev config file will have dev api url domain.
If your endpoints are same for all environments, you can export it from a separate common file.
2: And i have written a util function which switches the custom environment variable (we will set in next step) and return corresponding config file.

export function getEnvConfig(){
let config = null
switch(process.env.REACT_APP_ENV){
case “dev”:
config = require(“../config.dev”)
break;
case “qa”:
config = require(“../config.qa”)
default:
config = require(“../config.prod”)
}
return config
}

3: And inside my saga/thunk, i have imported and used the urls from config file.

const config = getEnvConfig()
const fetchUserUrl = config.default.baseURL + 'getusers'

4.On AWS Cognito secret manager, for each environment, I added a new secret with the name REACT_APP_ENV and value as my corresponding environment.

That's all. You can now access access your custom environment variable in your code using process.env.REACT_APP_ENV

Thank you!

Top comments (0)