When Does Your App Actually Read .env Files?
Have you ever thought about when does your software applications read environment variables from the .env files. Let's learn about it today.
There are two ways a environment variables get thrown in the application: during build time or runtime. Reading the .env files depend entirely on your technology stack. For frontend applications it’s necessary to read it during build time. For backend it should be read during runtime.
In frontend, browsers cannot access environment variables at runtime. So they need to be baked into javascript code in buildtime. When you run npm run build, your bundler (Webpack, Vite, Rollup) looks for references to process.env.MY_VAR in your code. It finds the value in your .env file and strictly finds-and-replaces the variable with the string value. If you change an environment variable in a frontend app, you must rebuild the application for the change to take effect. You cannot simply restart the server.
Since these variables are embedded into the HTML/JS, they are visible to anyone who uses “Inspect Element” in their browser. Never put secret keys (like AWS_SECRET_KEY) in frontend build-time variables.
In backend, when the application starts (e.g., via node index.js), it reads the .env file immediately (usually using a library like dotenv). The variables are loaded into memory on the server. If you change a variable, you only need to restart the application process. You do not need to rebuild the code.
Modern frameworks like Next.js complicate this because they run code on both the server and the client. Variables prefixed with specific identifiers (like NEXT_PUBLIC_ in Next.js or VITE_ in Vite) are inlined into the JavaScript bundle at build time. Variables without the prefix are kept secret. They are only available to the server-side code and are read at runtime.
If you are using Docker, there are two distinct phases for variables. Build time variables are available only while the Docker image is being built (e.g., npm install). These values do not persist in the final container. Runtime variables are available when the container starts (docker run). These are the variables your actual application will see.

