The real deal about env variables
By the time i realized it, i had already started to understand environment variables as an always trusted way to store secret values, which well, isn't completely wrong but not the most effective way to understand them, because env variables behave differently on backend and frontend, so understand this difference is super important to avoid some some tricky and risky situation.
But then how do we define what env variables are? The most intuitive way is to say that they are dynamically set values that are set in the environment where a program executes instead of directly in the code, making our applications easier to configure, so they have different behaviors depending on the value defined in that environment.
## value in the development .env file
API_URL=http://localhost:3000/
## value in the prod .env file
API_URL=https://yourdomain/
So since the value isn't explicit in the code, in fact we can say that the value is more secure when we use env variables, you make sure to put the .env file in the .gitignore so git won't track it, and in your backend application code, you use some libraries like dotenv so your app can use these values and since it's a backend application, this value never leaves the server, so yep we're safe so far :).
But when it comes to frontend applications, like React, Vite, etc, we still can use "env variables" but they don't remain secret. They are still env variables because their main functionality, having their value defined within the environment, still remains, but this it's when i remember what i highlighted in the beginning of how thinking of them as an always trusted way to store values can be dangerous.
How frontend deals with env variables
When we run the app, our frontend framework it will produce a static javascript bundle. For example, when we use this in the code:
VITE_SECRET_KEY=abc
const secretKey = import.meta.env.VITE_SECRET_KEY
console.log(secretKey)
This import.meta.env.VITE_SECRET_KEY is replaced with the literal value that we put in our .env file. So when we build and run our application:
npm run build
npx vite preview
Then open the browser's inspect:

Of course you shouldn't console.log your env variables in backend applications, much less at frontend ones, but on this code i just want to show how the literal value of your env variables is going to reach the client.
So i can't use them on the frontend?
Not exactly :p. Using environment variables in the frontend is still something you can do to take advantage of their flexibility and benefits, but only for non-sensitive configuration values such as API endpoints, app modes or even public service keys.
When your frontend needs to use some sensitive information, always use a backend middleware to handle that data securely, so the secret data stays hidden on the server while the frontend still gets access to the functionality it needs.
Top comments (0)