Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Anotheruser's avatar

Accessing $_ENV from JavaScript

Hi

I have my stripe publishable key defined in an environment variable in .env.local.php and in .env.php. I know the stripe publishable key can be placed within the javaScript directly and that works fine. However, as i need to use the Stripe.setPublishableKey('') in a number of javaScript classes I would like to use an environment variable as a point where i am able to update the key in a single location.

My problem is that when i use Stripe.setPublishableKey($_ENV['STRIPE_PUBLISHABLE']); within my javaScript files i get the error: Uncaught ReferenceError: $_ENV is not defined.

Is there a way to access the $_ENV or is it easier just to add the key in multiple js files manually?

Thanks

0 likes
6 replies
pmall's avatar
Stripe.setPublishableKey('{{ getenv('STRIPE_PUBLISHABLE') }}');

Env var are just line any other variable. You can print them in your javascript code.

Anotheruser's avatar

Hi pmall thanks for replying. However when i try that i get the following error: Uncaught SyntaxError: Unexpected identifier .

Any ideas?

Thanks.

RachidLaasri's avatar

The error is not on your setPublishableKey line, i believe you forgot curly braces or ";".

Can you post your code?

pmall's avatar

Oh, of course this should be in a blade template, not in a separate javascript file. Usualy my javascripts files have an init function, so i can initialize them in the blade template with data coming from php.

Anotheruser's avatar

@pmall Thanks, I don't suppose you have a quick example of that? i'm not having much luck at this end. Too many hours staring at the screen I cant get my mind round how to implement that and I know its probably really simple!

pmall's avatar
pmall
Best Answer
Level 56
#a_page_using_stripe.blade.php

@extends('layout')

@section('javascripts')
  HTML::script('js/my_stripe_script.js')
  <script type="text/javascript">
    $(document).ready(function(){
      InitMyStripeScript({
        key: '{{ getenv('STRIPE_API_KEY') }}', // Here the key is printed via blade and sent to the script
      });
  });
  </script>
@stop

@section('content')
your html
@stop
# public/js/my_stripe_script.js

function InitMyStripeScript(options){
  console.log(options.key); // Tada ! The key is displayed in js console
}

Please or to participate in this conversation.