Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access the laravel .env variables inside javascript?

I am currently using Algolia for my search engine inside a Laravel application, so whenever a record is created it is also sent to the Agolia database. Of course I want to separate my data in the Algolia database with a testset for local development and a production set for the live website. I have defined which indices of my Algolia database are being used in a JavaScript file.

Now I am wondering how do I react accordingly to my APP_ENV variable to change it depending on my current environment? Obviously I need to put stuff into an if statement in my JavaScript but how do I make my javascript access the .env variables properly?

Hopefully somebody can help me out.

Cheers.

like image 770
Stephan-v Avatar asked Aug 31 '25 04:08

Stephan-v


2 Answers

You can just echo out the env variable as a javascript string in your view:

<script>

var name = '{{ env('NAME') }}';

alert(name);

</script>

And your .env file would look like this:

NAME=Alex

like image 67
Agu Dondo Avatar answered Sep 02 '25 17:09

Agu Dondo


As the documentation suggests: you can use an env variable by prefixing it in your .env file with MIX_.

e.g: MIX_SENTRY_DSN_PUBLIC=http://example.com

After the variable has been defined in your .env file, you can access it from a javascript file with the process.env object.

e.g: process.env.MIX_SENTRY_DSN_PUBLIC

like image 43
TimothePearce Avatar answered Sep 02 '25 18:09

TimothePearce