Home > Back-end >  How can I pass environment variables by using dotenv in react app ? I get undefined
How can I pass environment variables by using dotenv in react app ? I get undefined

Time:11-10

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

.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.

CodePudding user response:

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.

  • Related