1

I see a lot of information about using environment variables on php files or twig templates, but I want to use them on javascript. I need to pass the environment, located on the .env file, to the Sentry init, located on assets/js/app.js.

How could I safely access this? Do I need to install dotenv or similar or is there a 'Craft way' of doing this?

I would appreciate any help on how to do this, or maybe a suggestion for a different approach.

1

The .env file is on the server and javascript is running in the client so you need to pass it through to javascript in your twig template inside a script tag.

{% set env = getenv('ENVIRONMENT') %}
<script>
    var myVariable = '{{ env|e('js') }}'
</script>

You probably don't need to escape it like in my example above, but good practice anyway. If you are then using the variable in that script you are good to go. From elsewhere on the page you can get the variable using:

document.addEventListener('DOMContentLoaded', () => {
    const myVar = window.myVariable;
});

Great article about this and more https://cruftlesscraft.com/passing-data-from-twig-to-javascript

  • The file I want to have the .env variables is not a twig template. That file is loaded on the head of the page, and I would like to avoid having a script tag there to set a global variable on the page. for a one time use. Plus if someone changes the order the variable might get lost and that's also not a good thing. – Tyrannogina regina Jan 6 '19 at 13:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.