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

  - config
    * config.js
  - .env

my .env file is


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


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.

Leave a Reply