Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VueJS Process shows undefined

Tags:

vue.js

Have an app that's built in Vue. Been trying to figure this out for a while. Im unable to access process variables. Have tried multiple things so far.

  • ensured my .env file is in the root directory
  • have run build and serve every-time I add variables to .env file
  • installed dotenv

Im using vue/cli 4.3.1 What am i missing?

[Edits]

  • Right now, my .env has only 1 entry enter image description here

  • Trying to access it in the created() method

    created: function() { console.log(process.env.VUE_APP_NOT_SECRET_CODE); }

  • Here is my folder structure

enter image description here

like image 624
cnatraj Avatar asked Oct 11 '25 20:10

cnatraj


2 Answers

If process is undefined

Check your NodeJs Version

You might want to update your NodeJs Version (and npm), remove the node_modules folder and hit npm install again. I read a few cases where this helped.

Recreate the env file

The .env file might be faulty in some way. Try deleting the file and re-creating it using console (like touch .env on linux)

If Variables are undefined

Check if you have the correct naming: VUE_APP_MYVAR instead of MYVAR

The most common error when it comes to Environment Variables inside Vue is the naming. When using env you have to prefix all variables with VUE_APP_, otherwise Vue won't include them.

More background info here : https://cli.vuejs.org/guide/mode-and-env.html. From the docs

Note that only NODE_ENV, BASE_URL, and variables that start with VUE_APP_ will be statically embedded into the client bundle with webpack.DefinePlugin. It is to avoid accidentally exposing a private key on the machine that could have the same name.

🚧 Make sure to not include any secrets (such as private API keys) in your app! Environment variables are embedded into the build, meaning anyone can view them by inspecting your app's files.

like image 149
Pascal Lamers Avatar answered Oct 14 '25 14:10

Pascal Lamers


While the other answers might be helpful, the eventual solution to this problem for me was, to actually only read the values at mounted. I am unsure why exactly, but this worked for me:

mounted: function (): void {
    console.log('App version: ' + process.env.VUE_APP_VERSION);
    console.log('Environment: ' + process.env.NODE_ENV);        
},

For showing them in the templated HTML output, I had to make sure, that undefined did not crash the process, and I have done it (the ugly way) like this (note the extra empty strings at the beginning in the computed functions):

<p title="App info">
    <small>App version: {{ version }} ({{ environment }})</small>
</p>
//....
computed: {
    version(): string {
        return '' + process.env.VUE_APP_VERSION;
    },

    environment(): string {
        return '' + process?.env?.NODE_ENV;
    },
},
like image 31
Marcel Avatar answered Oct 14 '25 16:10

Marcel