14

I have a react js project , but with typescript. I understand we can create .env file and have some configuration defined as such,

.env file

REACT_APP_SOME_CONFIGURATION = "some value" 

and use it in the code , without importing anything , like below

const configValue = process.env.REACT_APP_SOME_CONFIGURATION 

I tried this set up in my project , and it didn't work. is it because it is typescript? how to use .env file in such scenario.

arve
  • 569
  • 2
  • 10
  • 27
  • 1
    `process.env` does not exist on front end, you can use it only in your node backend – Yakir Fitousi Oct 20 '20 at 20:59
  • 3
    This is not true We use it also in Frontend – Yoel Oct 20 '20 at 21:06
  • @yoel are you sure about it? we had issue with similar case in our project because FE (react) could not consume process.env. what am i missing? – Yakir Fitousi Oct 20 '20 at 21:11
  • 1
    @YakirFitousi see here https://create-react-app.dev/docs/adding-custom-environment-variables/ – Yoel Oct 20 '20 at 21:17
  • @yoel wow, didnt know about it all.. thanks for the info! :) BTW, is it only for `create-react-app` ? – Yakir Fitousi Oct 20 '20 at 21:27
  • I not sure, Maybe it's related to react-scripts@ library – Yoel Oct 20 '20 at 21:43
  • 2
    @YakirFitousi hey yakir see here https://www.react-israel.co.il/%d7%a9%d7%99%d7%9e%d7%95%d7%a9-%d7%91%d7%9e%d7%a9%d7%aa%d7%a0%d7%99-%d7%a1%d7%91%d7%99%d7%91%d7%94/ OR here https://stackoverflow.com/a/59244254/9161478 – Yoel Oct 25 '20 at 09:50
  • @YakirFitousi it uses the Webpack Define plugin to make certain `process.env` variables available to the client-side code – Phil Oct 19 '22 at 00:43

4 Answers4

18

In TypeScript, you need to set the return value so if this string did so

const configValue : string = process.env.REACT_APP_SOME_CONFIGURATION 

OR

const configValue: string = (process.env.REACT_APP_SOME_CONFIGURATION as string);

Yoel
  • 7,555
  • 6
  • 27
  • 59
6

You can add this to your react-app-env.d.ts file

declare namespace NodeJS {
    interface ProcessEnv {
       //types of envs
        NODE_ENV: 'development' | 'production' | 'test';
        PUBLIC_URL: string;

    }
}
Heet Vakharia
  • 405
  • 4
  • 14
3

Update on March 2021: With React 17 and typescript, you don't need to set the return the 'configValue' value, just use the env variable like you did before. My .env file like this

REACT_APP_STRING=some_string_dont_have_quotation_mark
Dang Kien
  • 429
  • 6
  • 16
2

You could change this to a string or Undefined for a failing scenario like so

const configValue : string | undefined = process.env.REACT_APP_SOME_CONFIGURATION