0

I added react into django using webpack and when I created .env file in app_name/, I am trying to access environment variable like this process.env.base_url but I am getting undefined.

file structure

Django_React

  -- app_name
       -- src
       -- .env
       -- urls.py
       ...
       ...
  ...
  ...

webpack.config.js

const path = require("path");
const webpack = require("webpack");

module.exports = {
  entry: "./src/index.js",
  output: {
    path: path.resolve(__dirname, "./static/js"),
    filename: "[name].js",
  },
  module: {
    rules: [
      {
        test: /\.js|.jsx$/,
        exclude: /node_modules/,
        use: "babel-loader",
      },
      {
        test: /\.css$/,
        exclude: /node_modules/,
        use: ["style-loader", "css-loader"],
      },
    ],
  },
  optimization: {
    minimize: true,
  },
  plugins: [
    new webpack.DefinePlugin({
      "process.env": {
        NODE_ENV: JSON.stringify("development"),
      },
    }),
  ],
};

How can I create and access environment variable if react app is created like this ?

Anonymous
  • 77
  • 8
  • You'll need to properly inject the env variables into your compiled JS code through webpack. Can you show your webpack config? – Nico Griffioen Jan 25 '23 at 09:58
  • 1
    Have a look at [this question](https://stackoverflow.com/questions/46224986/how-to-pass-env-file-variables-to-webpack-config). Basically, use the dotenv plugin to load env variables from file into your webpack environment – Nico Griffioen Jan 25 '23 at 10:14

1 Answers1

0

Such issue could lead from naming convention.

According to React Doc - Adding Custom Environment Variables

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.

So, maybe you could try to

  1. add REACT_APP_ at the beginning of your environment variable name, like process.env.REACT_APP_base_url;
  2. restart the development server;
  3. access environment variable by process.env.REACT_APP_base_url.

Hope this helps.

celqaz
  • 26
  • 4
  • This solution did not work for me, I was able to solve from accepted solution given here (https://stackoverflow.com/questions/46224986/how-to-pass-env-file-variables-to-webpack-config) – Anonymous Jan 26 '23 at 01:39