28

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?

2
  • Is this done via ajax? You can access the env variables via the controller using the env() helper. Commented Sep 13, 2018 at 14:32
  • I've found this not to be secure, the values of the variables are brought through to the application app.js file Commented Jan 10, 2020 at 16:20

7 Answers 7

32

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

Sign up to request clarification or add additional context in comments.

5 Comments

myserver is windows but it didnt work in docker. i dont know why
In my case, it doesn't work neither way :/ with or without require('dotenv').config();
@Pathros you need to stop (php artisan serve) and run again for any changes in env file ... did you test it ? check it please
I am using Laravel Homestead. I have restarted the server many times and the MIX_ variables are not being identified / pulled. I don't understand why. What am I missing?
@Pathros what about your local or development pc?
17

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

4 Comments

thats worked for me by adding a new variable in env file with this prefix : MIX_ but need to restart php artisan serve and also restart npm run watch....
@darryl-e-clarke (if you want) can you accept the other new answer voted in the last three months by StackOverflow users? ;) stackoverflow.com/a/60378481/308578
Will i have to restart npm and serve command everytime I change url? If yes then how would i run npm run watch on cpanel if i dont have it?
11

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.

4 Comments

You should also add require('dotenv').config(); to the top of webpack.mix.js
thats worked for me without any require ... just add a new variable in env file with this prefix : MIX_ but need to restart php artisan serve and also restart npm run watch....
@Dazzle In my case, it doesn't work neither way :/ with or without require('dotenv').config();
did you npm install dotenv? Try recompile or delete node_modules folder and reinstall
2
 process.env.MIX_VAR /  process.env.MIX_STRIPE_KEY

It's will work without any settings. Just run this command

npm run prod

Comments

2

1. Solution by official documentation.

You may use Environment Variables https://laravel.com/docs/10.x/vite#environment-variables.

File .env:

VITE_SOME_NAME=some value

File *.js:

console.log(import.meta.env.VITE_SOME_NAME);

2. My working solution by logic and practice.

Passing any static and dynamic parameters to the JS script. Any script - not only modules! Assembly in one file.

File some_template-vue.blade.php:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Laravel + VUE</title>
    <script>
        window.scrf_token = '{{ csrf_token() }}';
        window.services = {
            myService: {
                constFromClass:        '{{ App\Models\MyClass::CONST_NAME }}',
                valueFromENV:          '{{ env('SOME_PARAM', 'default value') }}',
                urlFromRoute:          '{{ route('some/url') }}',
                urlFromRouteWithParam: '{{ route('some/url', ['param' => 'value']) }}'
            }
        }
    </script>
    <script src="{{ asset('js/app.js') }}" defer></script>
</head>
<body>
    <nav>
        <a href="{{ route('home') }}">Home</a>
    </nav>
    <div id="app">
    </div>
</body>
</html>

As result you will get in output:

<script>
    window.scrf_token = 'AbCdEfAbCdEfAbCdEfAbCdEfAbCdEfAbCdEfAbCdEf';
    window.services = {
        myService: {
            constFromClass:        'some value from class',
            valueFromENV:          'some value from ENV',
            urlFromRoute:          'some URL from Route',
            urlFromRouteWithParam: 'some URL from Route with param'
        }
    }
</script>

3. The idea of a Single Center of Responsibility through official practices.

File .env:

VITE_SERVICE_URL="/get_service"
VITE_SERVICE_SOME_PARAM="some value"

File routes/web.php:

Route::get(env('VITE_SERVICE_URL'), function () {
    return '<script type="module"> console.log(import.meta.env.VITE_SERVICE_SOME_PARAM); </script>';
})->name('service');

File vite.config.js:

import { defineConfig, loadEnv } from 'vite';
import laravel from 'laravel-vite-plugin';
import vue from '@vitejs/plugin-vue';

export default defineConfig(({ command, mode }) => {
    // https://v4.vitejs.dev/config/#using-environment-variables-in-config
    // Load env file based on `mode` in the current working directory.
    // Set the third parameter to '' to load all env regardless of the `VITE_` prefix.
    const env = loadEnv(mode, process.cwd(), '');
    return {
        define: {
            __APP_ENV__: JSON.stringify(env.APP_ENV)
        },
        plugins: [
            vue(),
            laravel({
                input: [
                    'resources/css/app.css',
                    'resources/js/app.js'
                ],
                refresh: true,
            }),
        ]
    }
});

1 Comment

This should be top comment and added as a solution IMO for newer versions ofc
0

This works for me

https://laravel.com/docs/8.x/mix#environment-variables

However, you will need to restart the task if the environment variable's value changes while the task is running: e.g If Watch is running then re-run it.

npm run watch

Comments

0

Follow these steps If you are using Laravel, Vue 3 with Vite:

You need to define your variables in the .env file with the VITE_ prefix like:

VITE_APP_NAME="${APP_NAME}"
VITE_PUSHER_APP_KEY="${PUSHER_APP_KEY}"

Inside your Vue component, you can now access the environment variables using:

import.meta.env.VITE_APP_NAME
import.meta.env.PUSHER_APP_KEY

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.