Doolan
Doolan

Reputation: 1641

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.

Upvotes: 68

Views: 79340

Answers (21)

Mr Alexander Ws
Mr Alexander Ws

Reputation: 227

If you are using CLI, use process.env.VUE_APP_YOUR_VARIABLE.

If you are using Vite, use import.meta.env.VITE_APP_YOUR_VARIABLE.

Don't forget to put your .env file in root directory.

I have Vue 3 using CLI and use process.env.VUE_APP_YOUR_VARIABLE it worked normally.

Upvotes: 0

Dave Sottimano
Dave Sottimano

Reputation: 1334

None of the solutions worked for me. Oddly, stopping dev server, deleting both .env and .env.local, restart dev server > recreate env files and then all of the variables from both files worked.

Upvotes: 0

Pawel Ka
Pawel Ka

Reputation: 1

I have struggled with this issue for the last few days and in may cause the guilty one was zsh terminal (maybe I have some plugin installed). It read my .env file (where I have empty values for all my keys) to the path and webpack took this values instead reading .env.development file. If I run the project directly from IntelliJ everything worked as expected, while from terminal I got wrong process.env values. Run following command

vue-cli-serve inspect

to check what settings your webpack has

my configuration vue 2.6 node 18.17

Upvotes: 0

Gabriel Reis
Gabriel Reis

Reputation: 11

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);

Upvotes: 1

saeed mohseni
saeed mohseni

Reputation: 21

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);

Upvotes: 0

Mr. Perfectionist
Mr. Perfectionist

Reputation: 2746

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

Upvotes: 1

Fred
Fred

Reputation: 1748

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.

Upvotes: 13

Valentine Shi
Valentine Shi

Reputation: 7800

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.

Upvotes: 2

Jaco Vd Wal
Jaco Vd Wal

Reputation: 51

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

Upvotes: 3

Leon A
Leon A

Reputation: 313

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;

Upvotes: 1

Fenn-CS
Fenn-CS

Reputation: 905

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.

Upvotes: 1

jovialcore
jovialcore

Reputation: 666

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

Upvotes: 1

Kayden van Rijn
Kayden van Rijn

Reputation: 2118

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

Upvotes: 0

Žilvinas
Žilvinas

Reputation: 150

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

Upvotes: 0

M3RS
M3RS

Reputation: 7500

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

Upvotes: 156

C.Christensen
C.Christensen

Reputation: 416

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:

Upvotes: 20

Tony
Tony

Reputation: 1432

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.

Upvotes: 4

Somang
Somang

Reputation: 33

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

Upvotes: 2

IwanC
IwanC

Reputation: 139

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

hope it helps

Upvotes: 13

Doolan
Doolan

Reputation: 1641

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.

Upvotes: 24

Bakhtiyor Sulaymonov
Bakhtiyor Sulaymonov

Reputation: 382

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)

Upvotes: 10

Related Questions