DEV Community

Ismail PE
Ismail PE

Posted on

2 2

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!

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay