Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I pass environment variables by using dotenv in react app ? I get undefined

This is my react fontend app. to pass data from node.js backend, I need to successfully pass API’s url. currently im setting the address to my localhost.

I am struggling to path process.env.API_URL to my config file.

my files structure is

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

.src
  - config
    * config.js
  - .env
.webpack.config.js

my .env file is

API_URL=http://localhost:3006

my config file is below but im getting "undefined" as my console result here. clearly variable is not passing successfully.

console.log(process.env.API_URL)

const config = {
  host: process.env.API_URL
};

export default config;

I have installed both "npm install dotenv –save" and "npm i dotenv-webpack"

Inside my Webpack.config.js is below. I feel like I am just so close to be working but I just cannot figure it out what’s the problem here.

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const webpack = require("webpack");
const dotenv = require('dotenv');
dotenv.config({ path: './.env' }); 


module.exports = {
plugins: [
    new webpack.DefinePlugin({
      'process.env.API_URL': JSON.stringify(process.env.API_URL),
    }),
  ],
};

any suggestions is appreciated. thank you.

>Solution :

Well you have .env in src folder and you are trying to access it on same level as webpackConfig. So move the .env file on the same level as config or fix your import.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading