Abhishek Kumar

When and Why to Use .env Files

"Learn how to manage environment-specific configurations and secrets in your development projects using .env files."

Abhishek Kumar

Table of contents

    Environment variables are a simple and powerful way to manage sensitive or environment-specific data in your applications. Using a .env file can help keep your code clean, secure, and portable.

    What is a .env File?

    A .env file is a plain text file that stores environment variables in a KEY=VALUE format. It’s not part of your source code but holds configuration data your app can access during runtime.

    Example:

    API_KEY=12345abcdef
    DB_URL=mongodb://localhost:27017/myapp
    PORT=3000
    

    Why Use a .env File?

    • Separation of config from code: Keeps your codebase clean and easier to manage.
    • Security: Secrets like API keys, DB credentials should never be hard-coded.
    • Flexibility: Different values for dev, test, and production environments.
    • Collaboration: Teammates can set their own config values without touching the code.

    How to Use .env in Your Project

    1. Install dotenv (for Node.js)

    npm install dotenv
    

    2. Load the .env File

    At the top of your index.js or app.js:

    require("dotenv").config();
    
    console.log(process.env.API_KEY);
    

    3. Use Variables in Code

    Instead of hardcoding:

    const apiKey = process.env.API_KEY;
    

    Best Practices

    • Never commit your .env file – add it to .gitignore.
    • Provide a .env.example file to show required variables without real values.
    • Don’t overload the .env file – keep it focused on config and secrets.

    In Frameworks

    • Next.js: Built-in support. Use NEXT_PUBLIC_ prefix for client-side vars.
    • React (CRA): Use REACT_APP_ prefix.
    • Laravel, Django, etc.: All support environment variables via .env.

    Using .env files is a small but impactful step toward writing clean, maintainable, and secure code. Start using them today to manage your app's configuration the smart way!