0

I want to use env variables in a React project CRA-4.0.3 with Typescript.

I did try many approaches(here, here, here , and some other) using dotenv, webpack and suggestions from different sources but I still get undefined.

But, I still get undefined, can someone point me in the right direction? I already spend a reasonable amount of time.

Update: I forgot to mention that I want them to be available in runtime, so, I can use them for E2E Test with Playwright and Jest as runner.

I'm using them in a structure like this /main/e2e/tests/file.spec.ts

.env

REACT_APP_ADMINUSER=user REACT_APP_ADMINPASS=pass

Thanks in advance

  • What is your .env look like? (Please hide sensitive info) – Ryan Le Sep 10 '21 at 11:07
  • also, please add how you are accessing the env variables – Mohit kumar Sep 10 '21 at 11:08
  • Please, post here your webpack config part with `DefinePlugin` settings if you don't use Create React App. https://webpack.js.org/plugins/define-plugin/ This plugin allows you to parse variables in React code. You should define variables that you want to pass in this webpack setting. Create React App provides DefinePlugin from scratch, so it should work out of the box. If you use CRA, please, make sure that you defined `.env` file in the root directory (besides package.json). Example: `A=1` (`.env`), `console.log(process.env.A)` (`App.jsx`) – Max Starling Sep 10 '21 at 11:09
  • 1. [Ryan] Description updated with .env 2. [Mohit] I have a a structure like this /main/e2e/tests/file.spec.ts 3. [Max] I do use Create React App – Mariano Vil Sep 10 '21 at 11:22
  • Did you resolve this problem? I have the same one. I will appreciate it if you help me. – nadia Mar 30 '23 at 18:51

1 Answers1

1

If you're using CRA as described here you just have to create a .env file in the root of your project, and populated it with something like REACT_APP_NOT_SECRET_CODE=abcdef.

Then in your app you can use that variable by using

console.log(process.env.REACT_APP_NOT_SECRET_CODE)

You don't need to add Webpack or other modules to the default configuration that comes with CRA

UPDATE: I see the edit of the question. Have the env variables exposed in runtime make a lot of difference since as default they're injected in build time.

I found this module https://github.com/kHRISl33t/runtime-env-cra that seems to make more easy the method described in the offical doc to have the variables in runtime

the_previ
  • 683
  • 6
  • 12