64

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.

M3RS
  • 6,720
  • 6
  • 37
  • 47
Doolan
  • 1,293
  • 1
  • 13
  • 28
  • 1
    Where you have copied the .env file? You should place it in the root directory as sibling to 'package.json' And hope u r accessing the values like this proceess.env.VUE_APP_URL – Tony Tom Apr 04 '19 at 09:49
  • 1
    My `.env` file is in the root directory and is a sibling to package.json and webpack.config.js. Calling `process.env.VUE_APP_URL` from a component returns `undefined` – Doolan Apr 04 '19 at 15:22
  • 2
    As some answers and comments, here and on [this github issue](https://github.com/vuejs/vue-cli/issues/1610) state, you might just need to restart the server. Some comment states that they had to run `npm run build` and `npm run dev` to make it work. There might be some cache or something similar (I'm not sure of that) But I am sure that hot reloading won't take into account any changes to .env files – Salim Mahboubi Mar 01 '21 at 17:46
  • 1
    Just to note, that .env files are publicly contained in the and should not contain private data, like eg. an API token. – Marcel Nov 27 '21 at 21:20

18 Answers18

147

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
M3RS
  • 6,720
  • 6
  • 37
  • 47
  • 9
    Even with HMR, this didn't work until I reloaded the server :/ – babis21 Jan 27 '20 at 16:23
  • 1
    Yes, HMR will not help with environment variables. The project needs to be rebuilt for changes to take effect. – M3RS Jan 28 '20 at 11:14
  • 2
    Also save the .env files. Every time you change them. And then restart again. – Robin Manoli Apr 28 '20 at 09:25
  • 1
    Another tip: Coming from Python I am conditioned to manually loading the .env file. It took me an embarrassingly long amount of time to realize that you do not need to explicitly load it anywhere. Just put it in the root folder, follow this answer's instructions, and let the magic work itself. – wfgeo Feb 12 '21 at 12:36
  • 8
    in my case it was the missing `VUE_APP_` prefix, thx – Yevgeniy Mar 10 '21 at 17:43
  • 1
    in my case, I've spent the whole day trying everything but I had my .env files in uppercase and that caused them to stop working after building the app in a pipeline – Žilvinas Mar 16 '21 at 12:08
  • 4
    It was the missing `VUE_APP_` prefix. So we can't use variables without this prefix in the `.env` file? – Nimish David Mathew May 05 '21 at 07:22
  • 1
    GOD! Why did no one tell me the variable names should start with `VUE_APP_` before? This thing drove me crazy this morning! THANKS! – hatef Jul 07 '21 at 07:21
  • 1
    IT works! Thank You. I had to SAVE (i forgot) the .env file : ) and i had to stop and close de browser. I restart the server, open the browser, and it works! – LUISAO Sep 15 '21 at 00:30
  • 1
    point 3 (restart server) fixed mine! Thanks! – Uncoke Jan 08 '22 at 15:48
  • 1
    If you are using Vue with Laravel Mix then replace ```VUE_APP_``` with ```MIX_APP_```. – Thabo Moyo Aug 17 '22 at 10:31
  • 1
    Restarting the server `npm run serve` worked for me – Nick_O Dec 08 '22 at 02:52
22

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.

Doolan
  • 1,293
  • 1
  • 13
  • 28
  • 2
    Thanks. I've been looking for a solution for several hours now. It's so strange as host and port was overwritten in config/index.js with a simple ```require('dotenv').config();```. I would never have guessed that I would need anything extra to use the variables in Vue components. – Jimmy Garpehäll May 15 '19 at 11:14
  • 4
    If someone is as stupid as I am, I missed the fact that the files should start with .env (for example, only the file name .env). Instead, I used the myconfig.env file, which was wrong. So in my vue app builded with cli 3.x it works without any dotenv.config or something like that – phil Sep 05 '19 at 12:04
  • 2
    I have searched a lot, but this is the only solution I tried which works with webpack without vue-cli. This did the trick for me. – Steven Jun 04 '20 at 18:20
18

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:

C.Christensen
  • 386
  • 4
  • 8
11

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

hope it helps

IwanC
  • 119
  • 1
  • 3
8

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)

5

I know that this question was asked about vue-cli 3, which generates code for Vue 2. But it is the top result if you google for "vue3 does not embed env" and similar queries, so I assume that a lot of people end up here when having trouble with process.env variables being undefined in their Vue 3 app.

So this is an answer about how to fix your Vue 3 env issues.

This is what causes the confusion

  1. If you google for env problems with vue, you end up in the vue-cli docs. But vue-cli was replaced by create-vue in Vue 3. There is a alert box at the top of the page that tells you this, but you've probably missed it.

  2. If you did not miss it and followed one of the two links in the box, you ended up in the Vue 3 tooling guide or in the create-vue repo. None of those resources mention env variables. But you learn that create-vue is based on Vite.

  3. If you follow that lead and google for "vite env", you end up in the vite documentation, where you finally find the answer:

    • env variables have to be prefixed with VITE_ to be compiled into the app (as opposed to VUE_APP_ in vue 2)
    • env variables will be available in import.meta.env in your app (as opposed to process.env in vue 2)

The latter one is what took me the longest to figure out.

This is how you need to do it

in an .env file in your project root:

VITE_MY_ENV_VAR=foo

The docs will also tell you about the different naming patterns for .env files in Vite. Very useful information if you work with different environments!

in your app:

const my_env_var = import.meta.env.VITE_MY_ENV_VAR

I hope this saves someone the time for figuring this out.

Fred
  • 1,103
  • 2
  • 14
  • 35
3

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.

Tony
  • 1,414
  • 3
  • 9
  • 22
2

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

Somang
  • 33
  • 6
  • this is weird.. it works for me as well.. but than I deleted the files created via `touch` and recreated using vs-code file creation UI... and it worked then... :D – Jyotirmay Apr 03 '23 at 09:03
2

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 by their names from .env files 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.

Valentine Shi
  • 6,604
  • 4
  • 46
  • 46
2

IF you are using VITE, use VITE_ in stead of VUE_APP

1

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

jovialcore
  • 601
  • 1
  • 5
  • 13
1

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.

Fenn-CS
  • 863
  • 1
  • 13
  • 30
  • This worked for me together with the `VUE_APP_` prefix in the variables' names. I also noticed that it will add the prefix in the name if you just name it something like `FOO`. In that case, it's accessible as `VUE_APP_FOO`. I'm not sure what I have to do the `.local` either. The [official doc](https://cli.vuejs.org/guide/mode-and-env.html#environment-variables) mentioned that `.env` is loaded in all modes. Maybe I understood it wrong? – Luyang Du Sep 27 '22 at 15:33
  • I lied about the auto add prefix thing. Just a misbehavior of mine during testing... Sorry about that – Luyang Du Sep 27 '22 at 17:03
1

It seems environment variables are not accessible in child Vue components. Best to declare them globally in main.js with Vue.prototype.env = process.env;

Leon A
  • 135
  • 1
  • 9
1

My mistake was that I was calling the file as "variables.env.development", but the right way is just ".env.development", with the dot starting the name. I removed the "variables" part and everything worked fine.

  • Inside the ".env.development" file: VITE_TEST=123f
  • In any file: console.log(import.meta.env.VITE_TEST);
0

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

Žilvinas
  • 151
  • 15
0

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

Kayden van Rijn
  • 1,939
  • 2
  • 6
  • 14
0

You can also get the env variable like this:

import.meta.env.VITE_APP_MDP_API_URL

Reference: https://vitejs.dev/guide/env-and-mode.html

Mr. Perfectionist
  • 2,605
  • 2
  • 24
  • 35
0

your variable files .env .env.production must be in root of project not in src Folder

VUE_APP_API_URL = http://localhost:7326/api/

const NODE_ENV = process.env.VUE_APP_API_URL;
console.log(NODE_ENV);