Add Laravel .env variable to Vue component
Asked Answered
G

6

27

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?

Gibbs answered 13/9, 2018 at 14:29 Comment(2)
Is this done via ajax? You can access the env variables via the controller using the env() helper.Issy
I've found this not to be secure, the values of the variables are brought through to the application app.js fileHitlerism
T
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

Tedtedd answered 13/9, 2018 at 14:59 Comment(4)
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....Regorge
laravel.com/docs/5.7/mix#environment-variablesNonviolence
@darryl-e-clarke (if you want) can you accept the other new answer voted in the last three months by StackOverflow users? ;) https://mcmap.net/q/497790/-add-laravel-env-variable-to-vue-componentRegorge
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?Oil
R
31

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

Regorge answered 24/2, 2020 at 14:54 Comment(5)
myserver is windows but it didnt work in docker. i dont know whyRegorge
In my case, it doesn't work neither way :/ with or without require('dotenv').config();Avian
@Avian you need to stop (php artisan serve) and run again for any changes in env file ... did you test it ? check it pleaseRegorge
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?Avian
@Avian what about your local or development pc?Regorge
T
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

Tedtedd answered 13/9, 2018 at 14:59 Comment(4)
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....Regorge
laravel.com/docs/5.7/mix#environment-variablesNonviolence
@darryl-e-clarke (if you want) can you accept the other new answer voted in the last three months by StackOverflow users? ;) https://mcmap.net/q/497790/-add-laravel-env-variable-to-vue-componentRegorge
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?Oil
E
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.

Ewold answered 13/9, 2018 at 15:2 Comment(4)
You should also add require('dotenv').config(); to the top of webpack.mix.jsOvary
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....Regorge
@Ovary In my case, it doesn't work neither way :/ with or without require('dotenv').config();Avian
did you npm install dotenv? Try recompile or delete node_modules folder and reinstallOvary
J
2
 process.env.MIX_VAR /  process.env.MIX_STRIPE_KEY

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

npm run prod

Javed answered 20/4, 2021 at 16:27 Comment(0)
S
1

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,
            }),
        ]
    }
});
Serif answered 16/2 at 11:29 Comment(0)
C
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
Clavus answered 22/12, 2021 at 10:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.