Gracie
Gracie

Reputation: 956

Importing environment variables into HTML with Netlify

I use environment variables within my JS code on my Netlify site and it works really well just setting them in "Build Environment Varibles", then using

process.env.EMAIL_SERVICE

I have an HTML file on Github that runs a couple of Netlify sites. I want to publish a PUBLIC_URL that is stored in Environment Variables for each site in Netlify. How could I use this whilst preserving and hiding my other "secret" environment variables that are stored on Netlify.

There is an article here about accessing them in the browser but that relies on /bin access which I do not have in Netlify

https://www.simonewebdesign.it/how-to-get-environment-variables-in-the-browser/

Any ideas?

Upvotes: 1

Views: 849

Answers (1)

talves
talves

Reputation: 14353

You can change the permission on the script to make it run if you want to use this method.

bin/env.sh

echo "env = {"
echo "  PUBLIC_URL: '$PUBLIC_URL'"
echo "}"

You setup the command to run in the site or the netlify.toml prior or as part of a build

chmod +x ./bin/env.sh && ./bin/env.sh > env.js

will output:

env.js

env = {
  PUBLIC_URL: 'your_value_from_environment_variable_PUBLIC_URL'
}

NOTE: There are other ways to get the env variables into your javascript using build tools also. This answer is to show how to change your shell script to have permission to execute on Netlify.

Upvotes: 1

Related Questions