Environment variable in Pages

I’m working with static html and JavaScript with some secret variables in it. Now I want to use Environment variable feature to keep my variable’s value secret and I want to access those variables in JavaScript file. I did set environment variable on the setting section. But I can’t access them in my JavaScript. I don’t want to use any framework like node js or anything because I don’t have enough knowledge about those.
I’m a little newbie. So please help me.

1 Like

Environment Variables are available only in the build phase of the website, not on the user’s browser when viewing the site.

This would make them not secret, of course.
The solution to keeping variables secret is to not use them in any public facing code, create a Pages’ Function and do the calculation there, with the environment variable you set-up (in the Functions section).

1 Like

If you’re working with static HTML and JavaScript files, you won’t be able to access environment variables directly from your JavaScript code, as environment variables are typically only available on the server side.

However, there are a few ways you can work around this limitation:

  1. Use a build tool like Webpack or Gulp to replace placeholders in your HTML and JavaScript files with the actual environment variable values during the build process. For example, you could replace a placeholder like {{API_KEY}} in your code with the actual API key value from the environment variable.
  2. Another option is to set the environment variable value in a script tag in your HTML file, and then access that value in your JavaScript code. For example:
... 1. In this example, the environment variable value is set as the `API_KEY` variable in a script tag, and then that value is accessed in the `your-script.js` file. 2. A third option is to use a server-side scripting language like PHP to generate your HTML and JavaScript files. In this case, you can access the environment variable value on the server side and pass it to your HTML and JavaScript files as a variable. For example: <?php $api_key = getenv('API_KEY'); ?> ... In this example, the `getenv` function is used to get the value of the `API_KEY` environment variable, and then that value is passed to the `your-script.js` file as the `API_KEY` variable.

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.