As a developer fresh out of training, I realised how there were many other things I do not know how to do. One of it was how to create
env variables for a static webpage.
Not everyone needs a Node environment or some other fancy stuff while creating their webpage. So in this small post, I'll share a quick solution if you intend to hide variables as you build your webpage. Do take note that this is meant for development phase only.
env variables are short for environment variables. Lifting up from Wikipedia, an environment variable is "a dynamic-named value that can affect the way running processes will behave on a computer". Dynamic-named simply means that the name resolution will be done at runtime.
Leaving those complicated definition aside,
env variables are widely used to store secrets and other variables you would like to keep away from prying eyes. An example of an
env would look something like this:
It's nothing new really. You just assign the value into the variable like always. The only difference is that this variable would be stored into a
.env file. This
.env file would also be listed in the
.gitignore file so as not to be pushed into your preferred Version Control System hosting service (such as GitHub).
The problem lies in creating this
script.js is the main JS file.
env.js is where you store your
env variable. Here are some important things to take note.
- In your HTML file, your
envfile should come first before your other JS files. This is because the other files would be dependent on the
- You would need to declare a Global variable within the JS file, fetching the
envfunction. You cannot directly input the
envfunction, into another function that's residing in another JS file.
.gitignoreor your secrets would be pushed out to your repository.
One of my worry in creating this solution is what happens when you deploy your code out. Usually, sites would have settings where you can place your
env variables. Do take note that you may need to change parts of your code when you do so.
I hope that this would help you in some way. It's not an elegant solution but it does what it's supposed to do. If you do have a simple alternative solution or feedback on why this might not be a good solution, don't hesitate to share!
Thanks for reading ☺.