6

So I'm trying to understand how to use .env to secure my api key & data for my login auth. I've followed the process of the dotenv package and the stackoverflow answer here.

What I did:

1. I installed the dotenv package

2. In my rootfolder, I added a .env with only one line:

API_AUTH=http://myapilink.com

3. In my App.js, I added following line:

require('dotenv').config()
console.log(process.env.API_AUTH)

However, console.log returns 'undefined', why is that? What have I missed?

Cédric Bloem
  • 1,447
  • 3
  • 16
  • 34

2 Answers2

18

You have to prefix your environment variables with REACT_APP_. See here.

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.

So instead of just API_AUTH it would be REACT_APP_API_AUTH instead.

And it will be exposed to your app as process.env.REACT_APP_API_AUTH.

Ana Liza Pandac
  • 4,795
  • 2
  • 24
  • 36
4

Dotenv only works on server side. It needs an environment to store the variables. Here, we extract the content of the .env file and reduce it to an Object and pass it to Webpack's DefinePlugin allowing us later usage (process.env.API_AUTH):

const webpack = require('webpack');
const dotenv = require('dotenv');

module.exports = () => {
  const env = dotenv.config().parsed,
    envKeys = Object.keys(env).reduce((prev, next) => {
      prev[`process.env.${next}`] = JSON.stringify(env[next]);
      return prev;
    }, {});

  return {
    plugins: [
      new webpack.DefinePlugin(envKeys)
    ]
  };
Khalt
  • 301
  • 2
  • 7
  • 1
    Thanks for your answer! But apparently the mistake I made was forgetting to use the 'REACT_APP_' prefix for my variables. – Cédric Bloem Jan 13 '19 at 13:08
  • In that one, you do not need the prefix. – Khalt Jan 13 '19 at 13:12
  • 1
    Env variables were easy in #React App done with CRA. But, I faced the issue doing with #webpack and it was resolved with your solution. However, there is the #EnvironmentPlugin, which is equivalent to #DefinePlugin but with lesser code. [Reference](https://webpack.js.org/plugins/environment-plugin/) – SHAHBAZ Apr 15 '20 at 06:51