Vue-cli 3 Environment Variables all undefined

I've tried all of the solutions out there but none seem to work for me. I just want to store some values in a .env file within my Vue app but simply trying to log process.env returns an empty object from within the component.

My .env file

VUE_APP_URL={api url}
VUE_APP_TOKEN={token}

My plan was to set these environment variables to data properties but it always returns undefined. If I do console.log(process.env.NODE_ENV) from webpack.config.js it will show that I'm in development but if I tried doing the same from within the component like

mounted() {
    this.$nextTick(() => {
      console.log(process.env.VUE_APP_URL);
    })
  }

It just returns undefined.


A few tips for people who land here:

  1. Make sure your .env files are in the project root folder (and not in say src/)
  2. Variable names should start with VUE_APP_ if to be statically embedded into the client bundle
  3. Restart the dev server or build your project for changes to take effect
  4. If you are migrating from a webpack based solution make sure that you replace : (from JSON config) with = (dotenv format). Easy to miss
  5. Make sure you've saved any changes to your .env files.
  6. In old Vue versions environment variables were defined in e.g. config/dev.env.js instead of the .env files in root

I figured it out - I had to install dotenv-webpack and initialize it in webpack.config.js which is odd because none of the docs stated that I needed to do so.


Install dotenv-webpack and configure the vue.config.js file as follows.

npm install dotenv-webpack --save-dev

Add this to your config file:

const Dotenv = require('dotenv-webpack');


module.exports = {
  configureWebpack: {
    plugins: [
      new Dotenv()
    ]
  }
}

In your .env file make sure you add VUE_APP_ before your variables like this:

VUE_APP_VAR1=example
VUE_APP_VAR2=value

Now you can access these variables in your Vue application:

console.log(process.env.VUE_APP_VAR1); // "example"
console.log(process.env.VUE_APP_VAR2); // "value"

Here some links for reference:

  • https://www.npmjs.com/package/dotenv-webpack
  • https://cli.vuejs.org/guide/webpack.html
  • https://cli.vuejs.org/guide/mode-and-env.html#environment-variables

so I use VUE_APP_API_URL (this doesn't work) then I change it to VUE_APP_APIURL (this works)

hope it helps