Next

Environment Configuration

  • Environment configuration in Node.js uses environment variables and dotenv to manage sensitive settings securely.
  • What are Environment Variables?

    Environment variables are external configuration values stored as key–value pairs, used by an application at runtime.

    They help separate code from configuration, making applications more secure and flexible.

    Examples:

    • Database URL

    • JWT secret key

    • API keys

    • Port numbers

    These values can change based on environment without changing code.

    Why Use Environment Variables

    • Prevents sensitive data exposure

    • Makes apps environment-independent

    • Easy configuration changes

    • Industry best practice

    🖼 Conceptual Flow

.env file → process.env → Application
  • 📘 Real-Life Analogy

    Think of environment variables like settings in your phone
    you change settings without changing the phone hardware.

    Using dotenv in Node.js

    What is dotenv?

    dotenv is a Node.js package that loads environment variables from a .env file into process.env automatically when the application starts.


    Example – .env File

Using dotenv in Node.js

dotenv loads environment variables from a .env file into process.env, helping keep sensitive configuration like ports, database URLs, and secrets secure.

PORT=5000
MONGO_URI=mongodb://localhost:27017/myapp
JWT_SECRET=supersecretkey
  • Why dotenv is Important

    • Keeps secrets out of source code

    • Makes configuration readable & manageable

    • Industry standard in Node.js projects

    Load dotenv

require("dotenv").config();
  • Access Variables

const port = process.env.PORT;
const dbUrl = process.env.MONGO_URI;
  • Important Rule

    • .env file should never be pushed to GitHub

    • Always add .env to .gitignore

Next