An environment variable is a name and value pair that exists in the system where the program runs. The code reads that value at runtime. This way, data that changes from one environment to another stays separate from the code.

How it works

When you open a terminal or start a server, the operating system passes the program a set of variables. The program looks up by name and receives the value.

The same code can run on your computer, on a test server and in production. What changes is only the value of each variable: the test database and the production database, for example.

In Node.js, reading is like this:

JavaScript · app.js
const chave = process.env.OPENAI_API_KEY;
if (!chave) throw new Error("Faltou a variável OPENAI_API_KEY");

To define a variable in the terminal:

export MINHA_CHAVE="valor-secreto"

These definitions are valid for the current session. For something permanent, use the hosting panel, the .env file or the system configuration.

Practical example

You created a script that calls an AI API. If you write the key directly in the code and push the project to GitHub, anyone can see and use that key, and the account gets expensive.

The right way is to store the key in an environment variable and read it in the code. In the repository you keep only the variable name, never the value. In a sample file, you list the expected names so other people know what to configure.

Another common case: the API address changes between test and production. With a variable like API_URL, you change the destination without touching any line of code.

What it's for

It is mainly used to protect secrets, such as API keys, passwords and tokens. It is also used to configure the behavior of the app in each environment, turn features on or off and define ports and addresses.

Hosting platforms and code agent tools use environment variables to receive keys from model providers. In general, this is the only place where these values should live.

Important cautions

  • Never send files with secrets to the repository. Put .env in .gitignore.
  • Do not print sensitive variables in logs.
  • If a key leaks, generate a new one and revoke the old one immediately.
  • Variables are plain text in the process. For very critical secrets, consider a secrets manager.

Following these points, you keep the project clean, portable and much more secure.