title: React - can't access environment variables in the server side
body: <p>I have created an app using Create-React-App on the client side and using express in the server side.  I have created an <code>.env</code> file for my environment variables where the <code>DB_USER</code> and <code>DB_PASSWORD</code> will be stored.</p>
  
  <p>In the server side, I would like to use a mongoose connection and the <code>.env</code> variables will be the credentials when connecting to the mongodb server.</p>
  
  <p>I'm getting undefined variables in the terminal console when I do <code>process.env.DB_USER</code>. Instead I'm getting my OS environment variables, and NodeJS variables.  However, I do see the variables when I do <code>console.log(process.env.DB_USER)</code> in chrome console/client side.</p>
  
  <p>I tried to install <code>dotenv</code>, <code>dotenv-webpack</code> and configure my <code>webpack.config</code> but nothing seem to be working.  I have also added <code>REACT_APP_*</code> as prefix to my variables, but still undefined values.  </p>
  
  <p>Also when I use <code>dotenv</code> and set this <code>require('dotenv').config()</code> in my <code>index.js</code> file, it complains about an <code>fs</code> dependency??</p>
  
  <p>I just can't get the environment variables to be read in the server folder, ideally it will be nice to have these variables read in the client and server folder.  Has anyone encountered this issue before?  I'm just learning how to use <code>Create-React-App</code> and <code>webpack</code>.  Your help will be appreciated!!!</p>
  
  <p>server.js</p>
  
  <pre><code>//server.js
  const express = require('express');
  const path = require('path');
  const router = require('./routes/routes.js')
  const app = express();
  const mongoose = require('mongoose');
  const bodyParser = require('body-parser');
  const user = process.env.REACT_APP_DBUSER;
  const password = process.env.REACT_APP_DBPASSWORD;
  
  //tells express frontend will reside in client folder
  app.use(express.static(path.join(__dirname, '../build')));
  app.use(bodyParser.json());
  app.use(bodyParser.urlencoded({ extended: true }));
  
  console.log('node', process.env);
  console.log(user);//this is undefined
  
  //connect to mongoDB
  mongoose.connect(`mongodb://${user}:${password}@ds141812.mlab.com:41812/note_app_db`, { useNewUrlParser: true });
  
  let conn = mongoose.connection;
  conn.on('error', console.error.bind(console, 'connection:'));
  conn.once('open', () =&gt; {
      console.log('connected to database');
  });
  
  //pass in routes from router const
  app.use('/',router)
  
  module.exports=app;
  </code></pre>
  
  <p>webpack.config</p>
  
  <pre><code>const webpack = require('webpack');
  const path = require('path');
  const CopyWebpackPlugin = require('copy-webpack-plugin');
  const Dotenv = require('dotenv-webpack');
  
  const config = {
      entry: __dirname + '/client/js/index.jsx',
      output: {
          path: __dirname + '/build',
          filename: 'bundle.js'
      },
      resolve: {
          extensions: ['.js', '.jsx', '.css']
      },
      module: {
          rules: [
          {
              test: /\.jsx?/,
              exclude: /node_modules/,
              loader: 'babel-loader',
              query: {
                  presets: ['@babel/preset-env', '@babel/react']
              }
          },
          {
              test: /\.(png|jpg|svg|gif|mp4|mov)$/,
              use: [{
                  loader: 'file-loader',
                  options: {
                      name: '/assets/[name]-[hash:8].[ext]'
                  }
              }]
          },
          {
              test: /\.scss$/,
              loader: 'style-loader!css-loader!sass-loader'
          }
          ]
      },
      devServer: {
          publicPath: '/',
          contentBase: __dirname + '/build',
          port: 5000,
          historyApiFallback: {
              index: 'index.html'
          }
      },
      plugins: [
          new CopyWebpackPlugin([
              { from: './client/index.html', to: './index.html' }
          ]),
          new Dotenv({
              path: './.env',
          }),
          new webpack.DefinePlugin({
              'process.env': {
                  NODE_ENV: JSON.stringify("development"),
                  REACT_APP_DBUSER: JSON.stringify(process.env.REACT_APP_DBUSER),
                  REACT_APP_DBPASSWORD: JSON.stringify(process.env.REACT_APP_DBPASSWORD)
              }
          })
      ]
  }
  
  
  module.exports = config
  </code></pre>
  
  <p>index.jsx</p>
  
  <pre><code>import React from 'react';
  import ReactDOM from 'react-dom';
  import App from './App';
  require('dotenv').config({path: '../../.env'});//is this how it supposed to look like???
  
  ReactDOM.render(&lt;App /&gt;, document.getElementById('root'));
  </code></pre>
  
  <p>package.json</p>
  
  <pre><code>{
    "name": "note_app",
    "version": "0.1.0",
    "private": true,
    "dependencies": {
      "@babel/core": "^7.1.5",
      "@babel/preset-env": "^7.1.5",
      "@babel/preset-react": "^7.0.0",
      "axios": "^0.18.0",
      "babel-loader": "^8.0.4",
      "body-parser": "^1.18.3",
      "copy-webpack-plugin": "^4.6.0",
      "css-loader": "^1.0.1",
      "dotenv": "^6.1.0",
      "dotenv-webpack": "^1.5.7",
      "env-cmd": "^8.0.2",
      "express": "^4.16.4",
      "file-loader": "^2.0.0",
      "mongoose": "^5.3.11",
      "node-sass": "^4.10.0",
      "nodemon": "^1.18.6",
      "react": "^16.6.1",
      "react-dom": "^16.6.1",
      "react-modal": "^3.6.1",
      "react-router-dom": "^4.3.1",
      "react-scripts": "2.1.1",
      "sass-loader": "^7.1.0",
      "style-loader": "^0.23.1",
      "webpack-cli": "^3.1.2"
    },
    "scripts": {
      "build": "react-scripts build",
      "test": "react-scripts test",
      "eject": "react-scripts eject",
      "webpack": "webpack --mode development",
      "dev": "npm run webpack &amp;&amp; nodemon bin/www"
    },
    "eslintConfig": {
      "extends": "react-app"
    },
    "browserslist": [
      "&gt;0.2%",
      "not dead",
      "not ie &lt;= 11",
      "not op_mini all"
    ]
  }
  </code></pre>
  
  <p>.env file</p>
  
  <pre><code>REACT_APP_DBUSER="username"
  REACT_APP_DBPASSWORD="password"
  </code></pre>
  
  <p>file structure
  <a href="https://i.stack.imgur.com/FKnsZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FKnsZ.png" alt="enter image description here"></a></p>