---
title: ".env File Explained: Read It in Python and Node, Keep Keys Out of Git"
description: "A .env file stores API keys and other config as plain text. Learn how to load it in Python and Node, use .env.example, and keep secrets out of Git."
url: https://cdnping.org/en/blog/dotenv-file-beginner
language: en
published: 2026-11-30
category: "Developer tools"
tags: [".env","python-dotenv","environment variables","API key","Git"]
source: cdnping.org
license: Free to quote and summarize with a link to the url above.
---
# .env File Explained: Read It in Python and Node, Keep Keys Out of Git

## What is a .env file?

A .env file is a plain text file in your project root. Each line is a `NAME=value` pair, used for configuration that varies by environment and should not live in code: API keys, endpoint URLs, database passwords. The program reads the file at startup, loads the contents as environment variables, and the code only refers to the variable names.

There is no formal standard for the .env format. It is a convention, and what actually does the work is the library that reads it. So you have two jobs: get your program to read it, and make sure it never gets committed to Git.

A typical .env:

```
OPENAI_API_KEY=sk-xxxxxxxx
OPENAI_BASE_URL=https://api.example.com/v1
DEBUG=false
```

The values here are placeholders; replace them with your own. Usually there are no spaces around the equals sign, and values that contain spaces or `#` are wrapped in quotes. For exact parsing rules, check the docs of the library you use.

## How do you read .env in Python?

The most common choice is python-dotenv.

1. Install it: `pip install python-dotenv`
2. Load it at the very top of your entry file:

```python
import os
from dotenv import load_dotenv

load_dotenv()  # By default, searches for .env starting in the calling file's directory and moving up

api_key = os.getenv("OPENAI_API_KEY")
if not api_key:
    raise SystemExit("Missing OPENAI_API_KEY, check your .env")
```

3. After that, SDKs read the environment variables they know about on their own. For example, the official OpenAI Python library reads `OPENAI_API_KEY` by default, so `OpenAI()` works with no arguments. To change the endpoint, see [How to change base_url in the openai Python library: three ways](/en/blog/openai-python-base-url-setting). If you're just starting to call APIs, read [Calling the OpenAI API from Python: from installing the SDK to printing a reply](/en/blog/python-call-openai-api-beginner) first.

Note that `load_dotenv()` does not override environment variables that already exist in the system by default. If you edited .env and nothing changed, first check whether you already exported a variable with the same name in your terminal. To override, pass `override=True`.

## How do you read .env in Node.js?

There are two ways.

The first is the dotenv package:

```bash
npm install dotenv
```

```js
import "dotenv/config";

console.log(Boolean(process.env.OPENAI_API_KEY)); // Only prints whether it exists, never the key itself
```

The second is Node's built-in support. Newer Node versions can load the file with a command-line flag:

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

This flag is available from Node 20.6; older versions don't recognize it, so check the official docs for your version. With it you don't need to install dotenv. For a complete API call example, see [Calling an LLM API from Node.js: a minimal working example](/en/blog/nodejs-call-llm-api-beginner).

## What is .env.example for?

.env.example is a template for .env. It lists which variables the project needs, with values left empty or set to placeholders, and it **can be committed to Git**. Someone who clones the project copies it and fills in their own values:

```bash
cp .env.example .env
```

```
# .env.example
OPENAI_API_KEY=
OPENAI_BASE_URL=
DEBUG=false
```

This way newcomers know what to configure without digging through the code, and the real secrets stay on your own machine.

## How do you keep .env out of Git?

Work through this checklist:

| Check | What to do |
| --- | --- |
| Ignore rule | Add a line `.env` to .gitignore. If needed, also add `.env.*` and allow the template with `!.env.example` |
| Already tracked? | Run `git ls-files .env`. Any output means it is already in the repository |
| Stop tracking | `git rm --cached .env`, then commit; the file stays on your disk |
| Check before committing | Look at `git status` and `git diff --staged`; don't blindly run `git add .` |
| In the history? | `git log --all -- .env`. Any entries mean it was committed at some point |

The key point: .gitignore only affects files that are **not yet tracked**. If .env was committed before, adding an ignore rule does nothing; you must run `git rm --cached` first.

## What if a key has already been committed?

Treat it as leaked. The order matters.

1. Go to the service's console and **revoke or rotate** the key, then generate a new one.
2. Update your local .env with the new key.
3. Then decide whether to clean up the Git history. Cleaning history (for example with git filter-repo) rewrites commits, so on a shared project talk to your teammates first. Even after cleaning, treat the old key as dead and don't keep using it.

Deleting the file in the latest commit is not enough; it can still be found in the history.

## What should you watch for when using .env for third-party endpoints?

Many tools need only two things to connect: an endpoint URL and an API key. Both fit naturally in .env. If you want to try different model gateways, put the URL and key in .env and leave the code unchanged. Environment variables for tools like Claude Code can also go in config files; for the hierarchy and precedence, see [Claude Code settings.json: hierarchy, precedence, and env configuration](/en/blog/claude-code-settings-json-guide). The difference between the token and key variables is covered in [ANTHROPIC_AUTH_TOKEN vs ANTHROPIC_API_KEY: what's the difference](/en/blog/anthropic-auth-token-vs-api-key).

If you don't have an overseas credit card, or just want one subscription that lets you switch between several models, take a look at [AGI Plan](https://agiplan.dev/startup). AGI Plan is a commercial partner of cdnping. It is a multi-provider LLM aggregation gateway with monthly subscriptions, payment in RMB, and no overseas credit card required; tools like Claude Code and Codex only need one endpoint URL changed. It is compatible with both the OpenAI and Anthropic API formats, so you just put the URL the gateway gives you and your own key into .env. The service states that it is not an officially authorized channel, and some models are available only outside China; see the [model page](https://agiplan.dev/models) for details.

If API calls fail, first check the [API status page](/en/status/openai) to see whether the problem is on the server side, then read [AI API latency from China](/en/learn/ai-api-latency-china) to judge whether the network is the cause.

## Next steps

1. Create .env and .env.example in your project.
2. Immediately check .gitignore and `git ls-files .env`.
3. Read the variables with the Python or Node code above and confirm they load.
4. To try an endpoint quickly, read [Calling the OpenAI API from Python: a beginner's guide](/en/blog/python-call-openai-api-beginner), or see the three-step setup instructions on the [AGI Plan beginner page](https://agiplan.dev/startup).
