Cover image for Use laravel .env variable in Vue

Use laravel .env variable in Vue

37shadesofgrey profile image Graham Morby | VueJs & Laravel Developer ・1 min read

This used to drive me nuts, many times I wanted a .env in Vue that was easy to use and maintain. So when I had a Laravel back end I found the best way was to use the .env that comes with Laravel and pull variables from there.

So how do we do it?

Let's say we have an API key and of course we do not want people to be able to see it on the Javascript end. We start by defining the variable in the .env. We define mixable variables using 'MIX'.

Enter fullscreen mode Exit fullscreen mode

So as long as we run

php artisan config:clear

we can now use the variable in our component.

To use it we simply call

Enter fullscreen mode Exit fullscreen mode

In the real world, it will look like so

data() {
   return() { 
     api_key: process.env.MIX_API_KEY
Enter fullscreen mode Exit fullscreen mode

and perfection! We can now use the laravel .env file to host and use any variables we don't want to store in javascript.


Editor guide

I have an issue I want to access variables inside .env through process.env.VARIABLE_NAME, but give me some error.I am working on laravel Pusher with VueJs.


import Echo from 'laravel-echo';

window.Pusher = require('pusher-js');

Vue.prototype.$echo = new Echo({
    broadcaster: 'pusher',
    key: process.env.MIX_PUSHER_APP_KEY,
    cluster: process.env.MIX_PUSHER_APP_CLUSTER,
    forceTLS: true

My Vue File

    mounted() {
        .listen('ExpenseNotification', (e) => {
            console.log('irfan ullah shakir');


[Vue warn]: Error in mounted hook: "TypeError: Cannot read property 'private' of undefined"

Code works fine to broadcast event to pusher, but have problem in receiving through 'Echo'


Have you re complied ?

npm run dev
yarn run dev 



Thank you I already solved it, here is my solution: