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?
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
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With