Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Laravel .env variable to Vue component

I would like to get access to an .env variable using Vue JS.

In my .env file I have added the 'MIX_' prefix to the var.

MIX_VAR=key

And then in the vue component, I have in the created():

console.log(process.env.MIX_VAR);

I keep getting undefined as the result.

I have tried clearing config cache, but still getting the same issue. Any ideas?

like image 741
Adnan Avatar asked Sep 13 '18 14:09

Adnan


3 Answers

in windows :

thats worked for me without any require in webpack.mix

... just add a new variable in env file with this prefix : MIX_

MIX_API_URL=http://laravel:8000

but need to restart php artisan serve and also restart npm run watch....

  let api_url = process.env.MIX_API_URL;
  console.log("my env variable:");
  console.log(api_url);

in linux or docker:

i didnt use them yet

like image 120
saber tabatabaee yazdi Avatar answered Sep 27 '22 17:09

saber tabatabaee yazdi


You must build your JS for the env variables to be replaced. You can do this with npm or yarn

https://laravel.com/docs/5.7/mix#running-mix

like image 44
Darryl E. Clarke Avatar answered Sep 27 '22 15:09

Darryl E. Clarke


Pulled from the official docs @ https://laravel.com/docs/5.6/mix#environment-variables


Environment Variables

You may inject environment variables into Mix by prefixing a key in your .env file with MIX_:

MIX_SENTRY_DSN_PUBLIC=http://example.com

After the variable has been defined in your .env file, you may access via the process.env object. If the value changes while you are running a watch task, you will need to restart the task:

process.env.MIX_SENTRY_DSN_PUBLIC

The most important thing to remember is that you have to use Laravel Mix for this to work. Mix is what is injecting the environment variable.

like image 37
Giovanni S Avatar answered Sep 27 '22 16:09

Giovanni S