35

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.

Stephan-v
  • 19,255
  • 31
  • 115
  • 201
  • 1
    You may create a restful resource to fetch your environment variables. Then send an ajax request to it. – krisanalfa Feb 28 '16 at 14:59
  • Do note, that allowing environment variables to be accessed without some sort of list as to what is allowed and what isn't. Would be rather dangerous... Seeing as most people have database and email server logins there. – Anees Saban Feb 28 '16 at 16:35

7 Answers7

51

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

Agu Dondo
  • 12,638
  • 7
  • 57
  • 68
  • 1
    Pretty much what I have done now. I was just hoping there would be a better or pre-made way since I think a lot of people might be running into this where you need to check your environment in javascript. Thanks for helping out! – Stephan-v Feb 29 '16 at 09:27
  • It will be syntax error because of order of apostrophe's You can either do this '{{ env("NAME") }}'; or do this "{{ env('NAME') }}"; – Mohammad Fahad Rao Aug 09 '21 at 05:25
  • 1
    No, it won't be an error, curly brackets are blade marks and the code between them gets rendered server side before running the javascript code around them. – Agu Dondo Aug 10 '21 at 06:35
43

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

TimothePearce
  • 1,128
  • 1
  • 11
  • 22
  • This is only true if your using vue components. If you're just using plain blade templates this is not accurate. – Luis M. Valenzuela Jan 15 '19 at 18:28
  • 2
    It works also with plain blade template with `{{ env('MIX_SENTRY_DSN_PUBLIC') }}`. – TimothePearce Jan 16 '19 at 14:55
  • https://github.com/JeffreyWay/laravel-mix/issues/1155 . Simply require mix and require the dotenv config file. Then it works out the box :) Any script can access the ENV vars this way. – simonw16 May 17 '19 at 22:32
  • 2
    you can even use expanded variables in the .env file like ```MIX_APP_ENV=${APP_ENV}``` and access it in js with ```process.env.MIX_APP_ENV``` so you don't have to write vars twice – Felix Geenen Sep 09 '20 at 12:32
  • 2
    This is the most correct answer. Remember to restart the compiling task after changing or adding a variable – BonisTech Mar 25 '21 at 22:35
  • My problem with this methodology is I need exactly I need to recompile, and I cannot do in my production environments. Moreover, Laravel is configured out of the box to commit the compiled files, so the env variables end to be practically hard coded. – Carlos Martínez Aug 14 '21 at 20:48
9

If accessing the env vars from outside of the main js file. You can do the following:

let mix = require('laravel-mix');
require('dotenv').config();

then:

let my_env_var = process.env.MY_ENV_VAR;

Requiring mix and the dotenv config gives you access. :)

simonw16
  • 960
  • 9
  • 25
2

If you're with vite, it uses dotenv to load additional ENV variables. Meaning if you prefix something in your .env with VITE_, you can later use it in your js as:

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

Example:

In .env:

MEILISEARCH_HOST=http://localhost:7700
VITE_MEILISEARCH_HOST=$MEILISEARCH_HOST # reusing the variable

In JS:

console.log(import.meta.env.VITE_MEILISEARCH_HOST); 
// ouputs: 'http://localhost:7700'

console.log(import.meta.env.MEILISEARCH_HOST); 
// outputs: undefined, so all your other .env vars are safe

More information can be found in Env Variables and Modes @ vitejs.dev

Ivanka Todorova
  • 9,964
  • 16
  • 66
  • 103
1

There are a lot of ways.

One of the best is to pass data from Controller to the view:

if ($app->environment('local'))
{
    // Here you can generate some <script></script> code or you could just generate
    // hidden div like <div id="environment" style="display:none">local</div>

}

or like this:

return view('myView')->with('env', $app->environment());

Or you could use Sessions:

\Session::put('env', $app->environment())

Of course you can create dedicated route and get it with Ajax, but I don't think it's a good way to do this in real life web application.

Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
1

A cleaner solution is to use the laracasts/utilities package to send your variables to your file.

Install it with the composer require laracasts/utilities command.

Then add use JavaScript; at the top of your controller.

And finally send your variable this way : JavaScript::put([ 'foo' => $bar ]);.

TimothePearce
  • 1,128
  • 1
  • 11
  • 22
1

First, make sure you can access your env file inside PHP file or blade file, you can view on this answer https://stackoverflow.com/a/60790227/13012364

Then, if your javascript file separated with your blade file, you can use window object to put your env value, example

window.APP_URL = `{{ config('app.APP_URL') }}`;

After that, you can access that env value in javascript file using window object

const app_url = window.APP_URL;
MyFRA
  • 366
  • 2
  • 5