Env variables for browser JavaScript
Arif Rawi
Posted on November 16, 2022
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.
What are env
variables
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:
secret_key=123456
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).
So what's the problem?
The problem lies in creating this env
variable for a static webpage. Which is, HTML5 with CSS and browser JavaScript. If you're using Python or Node JS, this could be resolved by simply installing the necessary packages.
For browser JavaScript however, I have yet to see a simple solution for this. Hence why I am proposing this solution.
The solution
env.js
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
env
file should come first before your other JS files. This is because the other files would be dependent on theenv
file. - You would need to declare a Global variable within the JS file, fetching the
env
function. You cannot directly input theenv
function, into another function that's residing in another JS file. -
Write your
env.js
into the.gitignore
or your secrets would be pushed out to your repository.
Last words
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 ☺.
Posted on November 16, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 29, 2024