DEV Community

Cover image for How to access the laravel .env variables inside javascript
Suresh Ramani
Suresh Ramani

Posted on • Originally published at

How to access the laravel .env variables inside javascript

What is .env?

Its environment variables file. In simple terms, it is a variable text file. In this file we set a variable with a value that you wouldn't want to share with anyone, the purpose of the file is kept secret and secure because in.

While working on your Laravel project, you may want to have some dynamic behavior based on your environment. For example, you want to set the database connection settings, or you want to specify the application's URL.

Laravels way of dealing with this is by providing a .env file. This file can contain any variable, which can hold different values on all your environments (dev, test, live, etc..), and can be read by Laravel. This gives a very convenient way of manipulating the behavior of our application in these different environments.

Please note that most information about the Laravel framework can be found in the official documentation. This article offers a little more detail in some cases.

In the Laravel framework, this place will be in the resources/js/bootstrap.js file. If you open this file for the first time, you can see the next lines:

window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
Enter fullscreen mode Exit fullscreen mode

In this very place, we can add any common header that we need (just like the X-Requested-With header). So, let’s do that and appropriate headers add here for the Authorization Bearer token and for the accepted content-type (for example):

window.axios.defaults.headers.common['Authorization'] = 'Bearer <TOKEN>';
window.axios.defaults.headers.common['Accept'] = 'application/json';
Enter fullscreen mode Exit fullscreen mode

But… it is so weird and not secure to keep the token in this file. So, yep, we could get this token from the environment variable. If you use a laravel-mixer for your project, you can achieve it easily.

First of all, you can add to your .env file a new variable, API_TOKEN for example:

Enter fullscreen mode Exit fullscreen mode

We can always use this variable in our project on the backend. But if you want to use it on the frontend — just add something like that in this very file:

Enter fullscreen mode Exit fullscreen mode

And now you can use this variable in your JS files like process.env.MIX_API_TOKEN. So we need to change an appropriate header in the bootstrap.js file:

window.axios.defaults.headers.common['Authorization'] = `Bearer ${process.env.MIX_API_TOKEN}`;
Enter fullscreen mode Exit fullscreen mode

That’s it.

Thank you for reading this blog.

Top comments (0)