Home Artificial Intelligence Automation Programming Cybersecurity Productivity Reviews About Contact
Programming

Environment Variables and .env Files: Keeping Secrets Out of Your Code

Environment Variables and .env Files: Keeping Secrets Out of Your Code
Table of Contents

     


    A hardcoded API key is the fastest way to lose a cloud account. Not because someone writes an exploit for it, but because the key is valid the moment the repository is cloned, forked, or leaked — and git remembers it forever, even after you delete it in a later commit.

    Environment variables and .env files are the standard fix. They are also easy to get wrong in ways that feel safe right up until they aren't. This walkthrough covers the setup that works in 2026, the mistakes that leak secrets anyway, and the one habit that prevents most of the damage.

    Why Secrets Do Not Belong in Code

    Source code is designed to be shared. It gets pushed to repositories, cloned onto laptops, forked into side projects, and copied into CI systems. A secret in a source file inherits every one of those copies.

    The problem is not just the current version of the file. Git stores every commit. If you commit a key, realize the mistake, and delete it in the next commit, the key is still in the history. Anyone with read access to the repository can check out the earlier commit and read the key in plain text. Deleting the file does not delete the history.

    Environment variables solve this by separating configuration from code. The code reads a value from the environment at runtime. The value itself lives somewhere else — a local file, a CI secret store, or a cloud secret manager — and never enters the repository.

    The Native Node.js Setup (No Package Required)

    Node.js has read .env files natively since version 20.6, which means you no longer need the dotenv package for the basic case [citation:1][citation:3].

    Create a file named .env in your project root:

    DATABASE_URL=postgresql://user:pass@localhost:5432/mydb
    API_KEY=your_real_key_here
    PORT=3000

    Then start your application with the --env-file flag:

    node --env-file=.env server.js

    Your code reads the values from process.env as usual:

    const dbUrl = process.env.DATABASE_URL;
    const apiKey = process.env.API_KEY;
    
    if (!dbUrl || !apiKey) {
      throw new Error('Missing required environment variables');
    }

    You can also load a file programmatically with process.loadEnvFile() if you prefer not to change your start command [citation:6][citation:13].

    If you are still using dotenv, it still works and still has features the native loader does not, including variable expansion and the ability to parse arbitrary files [citation:2][citation:9]. For a new project that only needs to load a .env file, the native flag is one less dependency.

    The .gitignore Rule You Cannot Skip

    Before you create the .env file, add it to .gitignore:

    .env
    .env.*

    The order matters. Adding the ignore rule after the file exists works, but only if you never staged it. If you already ran git add . with the file present, the secret is in the index and may already be in a commit.

    Commit a .env.example file instead. It lists the keys your application needs, with empty or placeholder values, so a new contributor knows what to set without seeing any real secrets.

    DATABASE_URL=
    API_KEY=
    PORT=3000

    This is the onboarding file. The real .env stays local and uncommitted.

    Fail Fast, Not Silently

    A missing environment variable should crash the application at startup, not produce a confusing bug later. The pattern is simple: check for required values and throw if they are absent.

    function requireEnv(name) {
      const value = process.env[name];
      if (!value) {
        throw new Error(`Missing required environment variable: ${name}`);
      }
      return value;
    }
    
    const dbUrl = requireEnv('DATABASE_URL');
    const apiKey = requireEnv('API_KEY');

    The alternative — a default value like process.env.API_KEY || 'dev-key' — is how a development placeholder ends up authenticating production traffic. Defaults are fine for non-secrets like a port number. For secrets, force explicit configuration.

    What Not to Put in a .env File

    A .env file is for configuration that changes between environments. It is not a general-purpose config system, and it is not a database.

    • No secrets in the .env.example. Empty values only. The example file is committed.
    • No logging of process.env. A debug dump or a crash reporter that serializes the environment will print every secret in plain text.
    • No committing .env "temporarily." There is no temporary commit. Once it is pushed, assume it is leaked.
    • No sharing .env over chat or email. Use a password manager or a secret manager for team sharing.

    If You Already Committed a Secret

    The order of operations matters more than the cleanup tool.

    Rotate the secret first. Generate a new key, update the .env file and any deployed environment, and revoke the old key. Do this before you touch git history. Once a secret has been pushed, assume it is compromised, and removing it from history does not change that assumption.

    Then remove it from history. Tools like git filter-repo or BFG Repo-Cleaner can rewrite history to remove the file, but rewriting history on a shared repository is disruptive. If the repository is private and the exposure was brief, rotation may be sufficient. If it was public, assume a bot already scraped it and rotate regardless.

    Then add the ignore rule. The .gitignore entry prevents the next commit from doing the same thing.

    When to Move Beyond .env

    For local development and a small deployment, an uncommitted .env file is enough. It stops being enough when you need any of the following:

    Need .env File Secret Manager
    Local development Works well Overkill
    Audit log of access No Yes
    Central rotation Manual Automated
    Team sharing Risky Built in
    Short-lived credentials No Yes

    Cloud secret managers — AWS Secrets Manager, Google Secret Manager, Azure Key Vault, HashiCorp Vault — fetch secrets at runtime using the platform identity your application already has, so there is no bootstrap secret to protect. They also log access and allow rotation without a redeploy [citation:1].

    For a freelancer running a single VPS, that is probably more machinery than you need. For a team deploying to a cloud platform, it is the baseline.

    Frequently Asked Questions

    Do I still need the dotenv package?

    No, for the basic case. Node.js reads .env files natively with --env-file since version 20.6 [citation:1][citation:3]. The package still has features the native loader does not, including variable expansion and programmatic parsing of arbitrary files, but a new project that only needs to load .env can skip it.

    What is the difference between .env and .env.example?

    The .env file holds your real secrets and is never committed. The .env.example file holds the same keys with empty or placeholder values and is committed, so contributors know what to configure.

    Can I use .env files in production?

    You can, but it is the weakest option. A file on the server can be read by anything with filesystem access, and it does not give you rotation or audit logs. For production, environment variables injected by the platform or a secret manager are safer.

    I deleted my .env from git. Is that enough?

    No. Git history retains the file until you rewrite history, and even then, if the repository was public, assume the secret is compromised. Rotate the secret first, then clean history if necessary.

    How do I share secrets with a teammate?

    Not over chat or email. Use a password manager with shared vaults, or a secret manager if you are deploying to a cloud platform. If you must share a .env file, encrypt it first and send the decryption key through a different channel.

    The setup is three lines: a .env file, a .gitignore entry, and a startup check that refuses to run without the values it needs. The discipline is in the order — ignore rule first, rotation before cleanup, and no defaults for secrets. A key that never enters the repository is a key that never needs to be rotated.

    Johnson Jones
    Johnson Jones
    Writer at AutomationEdge — covering AI, automation, and practical tools.