Coding

What Is a .env File? Format, Loading and Keeping It Out of Git

A .env file is a plain-text file of KEY=value lines that holds configuration such as database URLs and API keys for a project, usually during local development. Your app or a tool like python-dotenv, Node.js's --env-file flag or Docker Compose reads it and exposes the values as environment variables, which keeps secrets out of your source code.

What a .env file looks like

Here is a small one. All values are fake:

# fake values only
DATABASE_URL=postgres://app:example-password@localhost:5432/appdb
API_KEY="sk-test-1234567890"
DEBUG=true
export PORT=3000
GREETING='hello world' # trailing comment
BASE=/srv/app
LOG_DIR=${BASE}/logs
EMPTY=

The file sits in the project root and is named exactly .env, with the leading dot and no extension. The dot makes it a hidden file on macOS and Linux, so ls needs -a to show it.

Why projects use one

The Twelve-Factor App guidelines say an app should store config "in environment variables", because they are "easy to change between deploys without changing any code". Their test is whether "the codebase could be made open source at any moment, without compromising any credentials".

Setting a dozen variables by hand in every terminal is tedious, so a .env file collects them in one place for development. The code reads os.environ["API_KEY"] or process.env.API_KEY and never needs to know whether the value came from the file, the shell or a production server's settings. For setting variables without a file, see how to set environment variables.

The format rules (and where tools disagree)

There is no formal standard for .env files. Each loader has its own parser, and they agree on the basics:

  • One KEY=value pair per line.
  • Lines starting with # are comments.
  • Values may be wrapped in single or double quotes, which are removed.
  • A leading export is ignored, so the same file can be sourced in a shell.

They differ on the details. Node.js's parser also accepts backtick quotes, treats any text after # as a comment, and has supported multi-line values since v21.7.0 and v20.12.0. python-dotenv expands ${VAR} references but not bare $VAR, and supports escape sequences in double-quoted values. If a value contains #, spaces or $, quote it and test it with the loader you actually use. For example, python-dotenv 1.2.4 reads A=abc#def as abc#def but B=abc #def as abc, while C="abc #def" keeps the whole string.

Loading .env in Python (python-dotenv)

pip install python-dotenv
import os
from dotenv import load_dotenv, dotenv_values

print(dotenv_values(".env"))          # parse without touching os.environ
os.environ["DEBUG"] = "false"         # pretend the shell already set DEBUG
load_dotenv()
print("DEBUG after load_dotenv():", os.environ["DEBUG"])
load_dotenv(override=True)
print("DEBUG after override=True:", os.environ["DEBUG"])
print("PORT type:", type(os.environ["PORT"]).__name__)

Output with python-dotenv 1.2.4 and the file above:

OrderedDict({'DATABASE_URL': 'postgres://app:example-password@localhost:5432/appdb', 'API_KEY': 'sk-test-1234567890', 'DEBUG': 'true', 'PORT': '3000', 'GREETING': 'hello world', 'BASE': '/srv/app', 'LOG_DIR': '/srv/app/logs', 'EMPTY': ''})
DEBUG after load_dotenv(): false
DEBUG after override=True: true
PORT type: str

Four things show up here. The quotes, the export and the trailing comment were stripped. ${BASE} was expanded. load_dotenv() did not replace DEBUG, because existing variables win unless you pass override=True. And PORT is the string "3000", not a number. By default load_dotenv() looks for .env starting from the script's directory and moving up the tree.

Loading .env in Node.js

Node.js 20.6.0 and later can read the file itself, with no package:

node --env-file=.env app.js

As with python-dotenv, a variable already set in the environment takes precedence over the file. You can pass --env-file several times, and later files override earlier ones. The flag throws an error if the file is missing; Node.js 22.9.0 added --env-file-if-exists for optional files. On an older Node.js the flag doesn't exist. This is the real error from Node 18.18.0 on Windows:

C:\Program Files\nodejs\node.exe: bad option: --env-file=.env

On those versions, upgrade Node.js or load the file with a package such as dotenv.

.env in Docker Compose

Docker Compose automatically reads a .env file in the project directory, but uses it for interpolation: it fills ${VAR} placeholders in compose.yaml. The variables do not reach the container unless the Compose file passes them, for example:

services:
  web:
    image: example/web
    environment:
      - DEBUG=${DEBUG}

Shell variables take priority over the .env file, and docker compose config --environment shows the values Compose actually resolved. Docker Compose explained covers the rest of the file.

Keep .env out of Git

Add these lines to .gitignore, and commit a .env.example with the same keys and dummy values. Should .env be in Git? covers the reasoning and the team workflow in more depth; the short version is:

.env
.env.*
!.env.example

git check-ignore -v confirms which rule applies to each file. Real output from a scratch repository:

$ git check-ignore -v .env .env.local .env.example
.gitignore:1:.env	.env
.gitignore:2:.env.*	.env.local
.gitignore:3:!.env.example	.env.example

The ! line re-includes the example file, so git status lists .env.example as a new file while .env and .env.local stay hidden. If .env was committed before you added the rule, ignoring it now has no effect on the tracked copy; gitignore not working explains why. A secret that reached a pushed commit should be treated as leaked: rotate it first, then remove it from Git history.

Common .env problems

SymptomLikely cause
Value is None or undefinedThe file was never loaded, or it is in a different directory from where the app runs
Changed value has no effectThe same variable is already set in the shell or IDE, and the loader doesn't override by default
DEBUG=false still enables debugThe value is the non-empty string "false"; compare it explicitly
Value cut off at #Unquoted # started a comment; quote the value
File named .env.txtWindows hid the extension; rename it so the name is exactly .env

Frequently asked questions

Should I commit my .env file to Git?
No, not when it holds real secrets. Add .env to .gitignore and commit a .env.example file instead, with the same variable names and placeholder values, so other developers know what to fill in. If a .env with real credentials was already committed, removing it in a new commit is not enough: the secrets stay in history and should be rotated.
Is a .env file secure?
It is a plain-text file with no encryption, so it is only as safe as the folder it sits in. It keeps secrets out of your source code and repository, which is its main job. For production servers, a platform's secret store or environment settings are usually a better place for credentials than a file on disk.
Why are all my .env values strings?
Environment variables are always strings. PORT=3000 reaches your code as the text "3000", and DEBUG=false is the non-empty string "false", which is truthy in Python and JavaScript. Convert values explicitly, for example int(os.environ["PORT"]) in Python.
Why doesn't my .env value override the variable I set in the shell?
By default, both python-dotenv's load_dotenv() and Node.js --env-file leave existing environment variables alone, so a value already set in the shell wins. In Python, pass override=True to let the file win. Docker Compose also gives shell variables priority over the .env file.

Sources