notes.dt.in.th

The .env file is a text file that contains environment variables, commonly used store configuration settings for an application. It is written in a key-value pair format similar to a shell script.

Why doesn’t my application see the environment variables in the .env file?

By default, a shell does not load the .env file. This means that when you create a .env file, your application may not be able to access the environment variables defined in it, unless something causes the .env file to be loaded into your application’s environment.

  • Some runtimes loads .env files automatically.

    • Vite loads .env files automatically, making them available as import.meta.env. As a result, frameworks based on Vite also inherit this behavior, such as Astro and SvelteKit. Do note that for these frameworks, environment variables may be evaluated at build time or runtime1 and behavior can be different between development and production environments, so refer to the documentation for specifics.

    • Glitch, a platform for building web applications, automatically loads .env files in a project as a normal environment variable.

    • Docker Compose automatically loads .env files for the purpose of interpolation into the docker-compose.yml file. Note that this does not make the environment variables available to the containers managed by Docker Compose.

      More details for Docker Compose

      To make the environment variables available to the containers, specify the environment variable names in the environment section of the docker-compose.yml file. For example:

      services:
        myservice:
          image: myimage
          environment:
            - MY_ENV_VAR

      Docker Compose will pass on the contents of the MY_ENV_VAR environment variable (which may be automatically loaded from the .env file) to the container.

      Alternatively, if you want all environment variables from the .env file to be passed to the container, you can use the env_file directive in the docker-compose.yml file.

    • Bun loads .env files automatically.

  • Some runtimes lets you load a .env file, but it must be explicitly done.

  • Program your application to load the .env file.

    • Ruby apps can use the dotenv gem to load the .env file at startup.

    • Node.js apps can use the dotenv package to load the .env file at startup.

  • Run your application through a wrapper that loads the .env file.

    • dotenvx lets you run arbitrary commands with environment variables loaded from a .env file.

    • Docker lets you specify the --env-file for the container.

  • Load variables from .env file into the shell.

Footnotes

  1. Build-time environment variables are evaluated when the application is built and compiled/inlined into the final artifact. They are not changeable at runtime; changing these variables requires a rebuild.

    Run-time environment variables are evaluated when the application is running.