Ghulam Haider Farooqi
Ghulam Haider Farooqi

Reputation: 91

How to access env veriables in js file in laravel

I intigrate Stripe Api for testing how can i set public key in env. How to use in strip public key in js Public key:

 STRIPE_KEY=pk_test_IS796OfBm2ZFLfvBbwsXHJLK00fE6oqivk

and js file where use this veriable:

var stripe = Stripe({{ env('STRIPE_KEY') }});

Upvotes: 2

Views: 1471

Answers (2)

Muhammad Taufik Rizky
Muhammad Taufik Rizky

Reputation: 41

in LARAVEL if you use VITE, you can using "import.meta.env.key_name" for example .env like this

API_URL=https://mybackendurl.id/ 
VITE_API_URL="${API_URL}"

then in js (before vite build) you can call value from .env , in your app.js like this:

 const baseUrl =  import.meta.env.VITE_API_URL; 

then the value of your baseUrl will be "https://mybackendurl.id/ " after you run

npm run build

or you keep alive using

npm run dev

Upvotes: 2

Tim Lewis
Tim Lewis

Reputation: 29306

{{ }} is a .blade syntax control, and cannot be used in .js files.

If you have a <script> element inside a .blade.php file, then it will work, but otherwise you'll need to load the file into JS before including the .js file, or get the value via an ajax call.

For example, loading the variable to js before including the .js script:

example.blade.php:

<script type="text/javascript">
  let stripe_key = '{{ env("STRIPE_KEY") }}';
</script>
<script src="{{ asset('js/stripe.js') }}"></script>

Upvotes: 5

Related Questions