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.

2
  • 1
    You may create a restful resource to fetch your environment variables. Then send an ajax request to it. Commented Feb 28, 2016 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. Commented Feb 28, 2016 at 16:35

8 Answers 8

52

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

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

4 Comments

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!
It will be syntax error because of order of apostrophe's You can either do this '{{ env("NAME") }}'; or do this "{{ env('NAME') }}";
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.
it gives <empty string> in browser logs for APP_URL . E.g. I wanted to compose an url
45

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

6 Comments

This is only true if your using vue components. If you're just using plain blade templates this is not accurate.
It works also with plain blade template with {{ env('MIX_SENTRY_DSN_PUBLIC') }}.
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.
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
This is the most correct answer. Remember to restart the compiling task after changing or adding a variable
|
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. :)

1 Comment

Would this give you access to all env variables? Like from the console?
5

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

Comments

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.

Comments

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 ]);.

Comments

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;

Comments

1

I entered in project's config folder's app.php and found there a variable :

'url' => env('APP_URL', 'http://localhost'),

where APP_URL is already defined in .env So that I got in my blade file's script and wrote in:

<script/>
   console.log('{{ config("app.url") }}')
</script>

And got http://127.0.0.1:8000 in logs

as supposed to be.

So it turns out you have to define your variables in that app.php first

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.