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

5
  • What is your .env look like? (Please hide sensitive info) Commented Sep 10, 2021 at 11:07
  • also, please add how you are accessing the env variables Commented Sep 10, 2021 at 11:08
  • Please, post here your webpack config part with DefinePlugin settings if you don't use Create React App. 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) Commented Sep 10, 2021 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 Commented Sep 10, 2021 at 11:22
  • Did you resolve this problem? I have the same one. I will appreciate it if you help me. Commented Mar 30, 2023 at 18:51

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Yes, I did follow that, and still is undefined
Thanks, I'll try what you suggested

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.