Use Environment Variables

🔍 What: Environment variables are key-value pairs defined outside your code in a file like .env. These are accessed using process.env in Node.js.

💡 Why: To secure sensitive data (e.g., database credentials, API keys, secrets) by keeping them separate from your codebase. This also improves flexibility across environments (dev, test, production).

⚙️ How:

  1. Install dotenv:
    npm install dotenv
  2. Create a .env file in your root directory:
    PORT=5000
    DB_URL=mongodb://localhost:27017/myapp
    JWT_SECRET=your_jwt_secret
  3. Use the values in your Node.js project:
    require('dotenv').config();
    
    const express = require('express');
    const mongoose = require('mongoose');
    
    const app = express();
    
    mongoose.connect(process.env.DB_URL)
      .then(() => console.log("Connected to MongoDB"));
    
    app.listen(process.env.PORT, () => {
      console.log(`Server running on port ${process.env.PORT}`);
    });

📅 When: Use environment variables from the very beginning of your backend project to keep your application secure and environment-agnostic.

🛡️ Best Practice:
Never push your .env file to GitHub. Always add it to your .gitignore file:
.env

🔗 References: