DEV Community

Discussion on: Loading environment variables in JS apps

Collapse
 
asamolion profile image
Muhammad Osama Arshad

Hi there, nice article.

Just have a quick question. Does the dotenv script load the entire .env file into the client side?

If that's the case then wouldn't that expose sensitive data such as DB password etc?

Collapse
 
deammer profile image
Maxime

Hi Muhammad! The entire .env file is indeed loaded, so all the secrets (including database passwords, in your case) will be exposed on the client, if that's where your app is running. This would obviously be a huge problem in a production environment, but my use case was centered around local development.

Security depends heavily on your deployment pipeline and the kind of system you're building, and I don't want to go too deep on that topic in a comment, but I'll leave you with two things:

  1. If you're developing a client-side app, it should be making calls to an API, not a database. This way, even if the API key is leaked, you can control security by making the API read-only or having a strict CORS policy.
  2. You could use the code below to make sure your client-side app doesn't expose secrets:
if (process.env.NODE_ENV !== 'production') {
  require('dotenv').config();
}

Hope this answers your question!

Collapse
 
asamolion profile image
Muhammad Osama Arshad

I see. I was thinking of using this in production in my current client's app. Thanks for pointing this out.

Dodged a bullet there.

Collapse
 
fabiorosado profile image
Fabio Rosado • Edited

This might be silly but I was wondering exactly the same thing. If you can do console.log(process.env); I wonder if the values are automatically replaced by environment variables perhaps?

--EDIT--
I went ahead and read the link to the 12-factor app and this is exactly what happens. The values are replaced by environment variables with each deploy.

The twelve-factor app stores config in environment variables (often shortened to env vars or env). Env vars are easy to change between deploys without changing any code; unlike config files, there is little chance of them being checked into the code repo accidentally; and unlike custom config files, or other config mechanisms such as Java System Properties, they are a language- and OS-agnostic standard. - The Twelve-factor App

Collapse
 
asamolion profile image
Muhammad Osama Arshad

Very cool. Thanks for taking the time to answer.