In this lesson, you will learn how to use .env files to manage local development settings without hardcoding sensitive information into your source code.
Why use .env files?
When building Node.js applications, you often need configuration variables like database URLs, API keys, or port numbers. Hardcoding these directly into your JavaScript files is a security risk—especially if you push your code to a shared repository like GitHub. Instead, we use a .env file to store these values locally on your machine.
Creating your configuration
A .env file is a simple text file that lives in the root of your project directory. It follows a KEY=VALUE format. For example, create a file named .env and add:
DB_USER=admin
API_KEY=super-secret-key-123
PORT=3000
Because these files contain secrets, you should always add .env to your .gitignore file. This ensures your secrets stay on your computer and are never uploaded to version control.
Loading variables into Node.js
In a Node.js environment, these variables are not automatically available. You must load them into the process.env object. While there are popular community packages like dotenv to automate this, the fundamental mechanism is about ensuring your application has access to these specific runtime variables before your main logic executes.
By keeping these variables in a .env file, you can maintain different configurations for different developers on your team. Each person creates their own .env file locally, keeping their database credentials private while your application code remains universal and secure.
When your application starts, it looks for these variables. If a variable is missing from the environment, your code can fall back to a safe default, ensuring your application remains robust across different local setups.
Key Takeaway: Use .env files to isolate environment-specific secrets from your codebase and always include them in your .gitignore to prevent leaking sensitive information.