Search code examples
herokuwebpackenvironment-variablesdotenv

Heroku failed to load ./.env


My Problem

I am having trouble loading my environment variables on Heroku production. When pushing to Heroku I get following error message during the build script:

Failed to load ./.env.

Current Setup

I am using a .env file in the root of my app locally. I can succesfully load my environment variables using the dotenv-webpack plugin as follows:

//webpack.config

const Dotenv = require('dotenv-webpack')
module.exports = {
  // other settings...
  
  plugins: [
    new Dotenv(),
  ]
};

Loading the environment variables:

//server.js

require('dotenv').config();
console.log(process.env.MY_VARIABLE);

This works like a charm locally, but fails on Heroku.

Note: My config vars have been set on Heroku, so that's not the problem.


What I tried

I have already tried to force load the .env file from the root of my app like this:

new Dotenv({ path: path.resolve(__dirname, './.env') });

Someone also pointed out that the Heroku environment might be system wide environment variables so I tried to load them using:

new Dotenv({ systemVars: true });

Neither of these attempts worked for me.


My guess

I have noticed that Heroku saves their .env file under ./tmp/build_someRandomBuildId/.env. My guess is that the .env file is not on the root of the directory, hence why dotenv can't find it. There is also no way to hardcode the location of this file in my Webpack configuration as the build ID is randomized with every build. Is there a way to tell Webpack to look for the file in a dynamic location?


Solution

  • Today i stumbled upon this problem, i tried several solutions but none worked. My App was working locally but in production mode (heroku) it was not loading process.env correctly.

    then i found this https://www.npmjs.com/package/dotenv-webpack

    //webpack.config.js
      plugins: [
          new Dotenv({ systemvars: true }),
      ], 
    

    Just setting systemvars to true does the trick.. For now I have tested this using different keys for the .env file and the heroku dashboard; They are not connected, and they replace themself correctly in production or dev mode.

    Use the package "dotenv-webpack" instead of "dotenv".

    I hope this saves some time to anyone facing the same problem