Use Env variables in view script

#1

I am importing a script from /public/stripeElement.js into a view.edge file using {{ script('path/to/file') }}

I want to access some variables stored in my .env file within the script file, but I am not able to use require(‘Env’) or require(‘dotenv’).config() as I get the error require is not defined.

Is it possible to access the .env file in this scenario?

0 Likes

#2

I don’t think it is possible and also I think thank you should not do that. Because in MVC architecture, you should send all parameters from controller to view layer. It is a best practice.

0 Likes

#3

Are you trying to use require inside the the edge template itself? Assuming you’re using controller’s, you should be able to access the environment variables from there, and pass specifically what you need to the the edge template.

0 Likes

#4

The script tag will load the Javascript that is executed in the browser and ofcourse the browser scripts cannot access content on the server.

Ideally environment variables are used to store secrets (data that should be kept private) or other config that changes based upon the environment your server is running in.

Now your client side Javascript shouldn’t depend on Environment variables at all. Maybe you can share your actual use case

0 Likes

#5

@virk I am integrating Stripe payments into my site. I can’t include in the javascript directly in the .edge files because they fail to compile, so I have included them with {{ script('path/to/file') }} as mentioned above.

As you will understand, stripe requires that I include my API key in the Javascript, which as you said should be stored in the .Env file, but this is where I am struggling as the Javascript file can not parse the .Env file, because it’s not being processed by node.

0 Likes

#6

Why not simply put it inside your frontend Javascript directly?

0 Likes

#7

@virk I have tried to put the javascript directly into the .edge but the the edge file will then not compile. I’m not sure but I think it might be because it the script has to inject html elements from the stripe domain into place holders in the template.

0 Likes