Search code examples
reactjsenvironment-variablescreate-react-app

Not able to fetch .env urls to my component on my react project


I am using 3 .env file like .env.prod, .env.dev and .env. But not able to fetch the url to my component.

I am using react 16.9.

Can you please help me why I am not able to fetch it?

in my .env / .env.dev files

loginUrl = = "http://localhost:8080/api/2.0/admin/auth/login"

in my package.json files

 "scripts": {
    "start": "cp ./.env.dev .env && react-scripts start",
    "build:dev": "cp ./.env.dev .env && react-scripts build",
    "build:stage": "cp ./.env.stage .env && react-scripts build",
    "build:prod": "cp ./.env.prod .env && react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },```

Inside my component, when I am printing it it is giving undefined.

console.log(process.env.loginUrl) is giving undefined

Solution

  • Using react-script

    Looking at react script adding-custom-environment-variables documentation, variables are automatically loaded from .env if:

    Note: You must create custom environment variables beginning with REACT_APP_. Any other variables except NODE_ENV will be ignored to avoid accidentally exposing a private key on the machine that could have the same name. Changing any environment variables will require you to restart the development server if it is running.

    Seams like the problem come from the name of your variable, try renaming in REACT_APP_LOGIN_URL

    Note: this feature is available with [email protected] and higher.

    If using Webpack instead of react-script

    You need to use webpack DefinePlugin to inject environments variables in your code.

    In your webpack.config.js file :

    require("dotenv").config(); // will load .env file in process.env
    const webpack = require("webpack");
    ...
    
    plugins: [
        ...
        new webpack.DefinePlugin({
          "process.env": {
            NODE_ENV: JSON.stringify("production"),
            SENTRY_DSN: JSON.stringify(process.env.SENTRY_DSN),
            BUILD_DATE: JSON.stringify(new Date()),
            TRAVIS_COMMIT: JSON.stringify(process.env.TRAVIS_COMMIT)
          }
        }),
       ...
    ]
    

    Make sure you have strings only as if the value isn't a string, it will be stringified (including functions).

    Then in your code, you can call console.log(process.env.NODE_ENV)