Can't access variable key inside .env (dotenv package React)

Viewed 9372

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?

2 Answers

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.

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)
    ]
  };
Related