process & configuration in nodejs
basic · Node.js — Server-side JavaScript
n Node.js, process.env is a built-in global object that returns an object containing the user environment. It is the primary way to handle configuration and secrets without hardcoding them into your source code. 1. What is it used for? When you build an application, you often have values that change depending on where the code is running (e.g., your laptop vs. a production server in Hyderabad). Common uses include: Database Credentials: Usernames and passwords. API Keys: Secret tokens for services like Stripe or AWS. Port Numbers: Deciding which port the server should listen on. Environment Mode: Switching between development and production . 2. Basic Usage You can access any environment variable by its key. Note that keys are case-sensitive, though by convention, they are always written in UPPER_SCASE // Accessing the PORT environment variable const port = process.env.PORT || 3000; console.log(`Server will run on port: ${port}`); 3. Setting Variables There are two main ways to set these variables: A. Terminal (Temporary) You can set a variable just for a single execution of your script. Linux/macOS: PORT=5000 node app.js Windows (Command Prompt): set PORT=5000 && node app.js Windows (PowerShell): $env:PORT=5000; node app.js B. Using .env Files (Recommended) Managing variables in the terminal is messy for large projects. Instead, developers use a .env file and a third-party module called dotenv . Create a .env file in your root directory: PORT=5000 DATABASE_URL=mongodb://localhost:27017/mydb STRIPE_KEY=sk_test_4eC39HqLyjWDarjtT1zdp7dc Load it in your code: require('dotenv').config(); // Loads variables from .env into process.env console.log(process.env.DATABASE_URL); 4. The NODE_ENV Convention NODE_ENV is a specific environment variable used by many libraries (like Express or React) to optimize performance. development : Provides verbose error messages and unminified code (slow but helpful). production : Strips out debugging code and optimizes for speed. Example Check: if (process.env.NODE_ENV === 'production') { console.log("Running in high-performance mode."); } else { console.log("Running in development mode with full logging."); } 5. Critical Security Warning Never commit your .env file to version control (GitHub/GitLab). If you push your .env file, your secret API keys and database passwords become public. Fix: Add .env to your .gitignore file. Pro-Tip: Create a .env.example file with the keys but empty values so other developers know which variables they need to set up. 6. Process vs. OS Environment process.env does not actually change the environment variables of your operating system. It creates a copy for that specific Node.js process. Once the process ends, those temporary variables disappear.