Vue-cli 3 Environment Variables all undefined

vue.jsVuejs2Environment VariablesVue CliVue Cli-3

vue.js Problem Overview


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.

vue.js Solutions


Solution 1 - vue.js

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

Solution 2 - vue.js

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.

Solution 3 - vue.js

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:

Solution 4 - vue.js

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

hope it helps

Solution 5 - vue.js

If your vue-cli version is higher than 3.x and you put your .env files in root directory like said in comments. Than you can access your environmental variables from components (like this process.env.VUE_APP_YOUR_VARIABLE). As said in vue-cli docs

> Only variables that start with VUE_APP_ will be statically embedded into the client bundle with webpack.DefinePlugin. You can access > them in your application code: console.log(process.env.VUE_APP_SECRET)

Solution 6 - vue.js

I put my .env file in the root directory and appended each variable with VUE_APP_.

To demonstrate this, for example, if the variable you want to use is API_BASE_URL

In your .env file, you put the variable as VUE_APP_API_BASE_URL=baseurl/api/v1

To access it in your files, you do process.env.VUE_APP_API_BASE_URL.

CAVEAT:

Never put any sensitive information you don't want anybody to see, on your front-end. The most common thing you won't want anybody to see (as regards web development) is your API Key. There are real consequences to doing this. This is one such example of someone who has been burned exposing API keys to the public.

However, even if you put your sensitive data in a .env file and add the .env file to a .gitignore file (hence not pushing it to a Git repository hosting service e.g Github, BitBucket, Gitlab etc.), your data is still not safe on the front-end. It's only safe when this is done on back-end code as it will be hosted on a server.

In the front-end, anyone who is determined enough can find your sensitive information. All your information is available on a browser and all that person needs to do is to open the dev tools and check the Sources tab, and BOOM all your sensitive information is laid bare.

Environment variables on the front-end are only useful when you want one reference point for NON-SENSITIVE information, such as a BASE URL, as seen in the example above. A BASE URL can change during the course of development and you won't want to change all references in the application folder manually. It is tedious plus you may miss a few, which would lead to errors.

If you want to avoid exposing your API keys and other sensitive information you may require on the front-end, take a look at this article.

Solution 7 - vue.js

Vue CLI dotenv usage suffers the inability to provide the .env variables other than prefixed with VUE_APP_. This is OK but this is far not enough to satisfy any even little serious web project that wants to conveniently and securely manage its (sometimes huge) list of variables for different environments.

Here is the solution that makes use of .env variables as convenient as on backends with dotenv.

With this solution you could access your MY_EXTERNAL_API_KEY from your .env[.environment] file in your code like this const key = process.env.MY_EXTERNAL_API_KEY.

It provides:

  1. The convenience of using non-prefixed with VUE_APP_ variables' names and use .env variable expansion feature (use ${VARNAME} kind of variables)
  2. The necessary security: your variables are neither available at browser console with console.log(pocess.env.MYVAR) at run time nor are explorable via text search within the built application's JS bundle.
  3. You can still use original Vue CLI solution along;

For this use dotenv-webpack plugin in your vue.config.js as follows:

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

const envPath = function() {
    return (!process.env.NODE_ENV || (process.env.NODE_ENV === 'development')) ?
        './.env' :
        `./.env.${process.env.NODE_ENV}`;
}

const dotenvArgs = {
    expand: true,
    path: envPath()
};

module.exports = {
   //... some other config here
    configureWebpack: {
        plugins: [
            new Dotenv(dotenvArgs)
        ]
    }
};

Here:

There are other useful dotenv-webpack options you could use.

I believe this solution is good enough to fully satisfy most frequent use cases.

NB: Remember as you pass your secret variables set via .env into HTTP requests from your front-end (e.g. an API key in a call to some external API) they are visible to any one who knows where to look. To diminish security risks for this situation there are different solutions.

Just to hint you have either to:

  • provide only publicly open data via your application;
  • or authenticate your application (or parts of it) via some authentication service (login/password + JWT|sessions, external authentication providers e.g. Facebook, Google etc.);
  • or resort to server-generated application.

But this is the whole separate subject.

Solution 8 - vue.js

This is what worked for me. I previously created my .env.development and .env.production files in the root folder by manually by right-clicking in the Exploer in VS Code and adding a new file. This kept giving me undefined.

I deleted the files and first installed npm install touch-cli -g Once installed, i added the environment files as such touch .env.production and touch .env.productionand itworks. So I think there's a difference between how these env files are generated.

NOTE: I do not have webpack installed. Just using the vue cli to build

VS Code ExplorerChrome Developer Tools

Solution 9 - vue.js

if you are cominng from VUE-cli-2 or you just cloned/installed an old vuejs project and you can't find .env file, this article explains what you have to do to set your .env variables as they environment files are probably located in config/dev.env.js (Note: this is peculiar to Vue-cli-2 files)

Here is also a solution and a detailed explanation for Vue-cli-3 .env related issue

Solution 10 - vue.js

It might also help: make sure your .env files are in lowercase letters because in Linux it won't work even if it is working in windows

Solution 11 - vue.js

The answer provided here helped me out. I'm using Laravel with an odd setup for Vue 2.x. The project is also using Laravel Mix. Here's the solution:

Inside of your .env file, which is a sibling of package.json:

MY_ENVIRONMENT_VARIABLE=my_value

Inside of webpack.mix.js:

const { mix } = require('laravel-mix');

mix.webpackConfig(webpack => {
    return {
        plugins: [
            new webpack.EnvironmentPlugin (
                ['MY_ENVIRONMENT_VARIABLE']
            )
        ]
    };
});

Afterwards, an npm run dev or npx mix should allow you to use these variables.

Credit: Thorsten Lünborg

Solution 12 - vue.js

What worked for me was changing from .env to .env.local. Haven't investigated WHY but I checked an old project and saw that I had a .env.local instead and did same for this project that would not pick the values from .env irrespective of whether vars where prefixed with VUE_APP and it worked.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDoolanView Question on Stackoverflow
Solution 1 - vue.jsM3RSView Answer on Stackoverflow
Solution 2 - vue.jsDoolanView Answer on Stackoverflow
Solution 3 - vue.jsC.ChristensenView Answer on Stackoverflow
Solution 4 - vue.jsIwanCView Answer on Stackoverflow
Solution 5 - vue.jsbakhti_UZBView Answer on Stackoverflow
Solution 6 - vue.jsTonyView Answer on Stackoverflow
Solution 7 - vue.jsValentine ShiView Answer on Stackoverflow
Solution 8 - vue.jsSomangView Answer on Stackoverflow
Solution 9 - vue.jsjovialcoreView Answer on Stackoverflow
Solution 10 - vue.jsŽilvinasView Answer on Stackoverflow
Solution 11 - vue.jsKayden van RijnView Answer on Stackoverflow
Solution 12 - vue.jsFenn-CSView Answer on Stackoverflow