Environment Variables
Imagine you have a recipe that calls for secret ingredients. You wouldn't write those secrets on the recipe card that everyone can see. In the same way, your Node.js application has secrets – database passwords, API keys, and other configuration that shouldn't be hardcoded in your source code.
What are Environment Variables?
Environment variables are dynamic values that can affect the way running processes behave on a computer. They are set outside your application and can be different in different environments (development, testing, production).
Think of environment variables as post-it notes stuck to your computer. Your app can read them, but they're not part of the app's code.
Why Use Environment Variables?
- Security: Keep secrets out of your code.
- Configuration: Different settings for different environments.
- Portability: Same code works everywhere with different config.
- Best Practice: Industry standard for configuration.
Accessing Environment Variables in Node.js
Node.js provides access to environment variables through the `process.env` object.
<!-- Read an environment variable -->const port = process.env.PORT || 3000;const dbPassword = process.env.DB_PASSWORD;
console.log('Server will run on port:', port);Setting Environment Variables
You can set environment variables in your terminal before running your app.
On Mac/Linux:
export PORT=5000export DB_PASSWORD=secret123node app.jsOn Windows (Command Prompt):
set PORT=5000set DB_PASSWORD=secret123node app.jsOn Windows (PowerShell):
$env:PORT=5000$env:DB_PASSWORD="secret123"node app.jsThe Dotenv Solution
Typing environment variables every time you run your app is tedious. The `dotenv` package lets you store them in a `.env` file.
npm install dotenvCreate a `.env` file in your project root:
PORT=5000DB_HOST=localhostDB_USER=rootDB_PASSWORD=secret123DB_NAME=myappJWT_SECRET=my-super-secret-jwt-keyIn your `app.js`, load the dotenv config at the very top:
require('dotenv').config();
const port = process.env.PORT || 3000;const dbConfig = { host: process.env.DB_HOST, user: process.env.DB_USER, password: process.env.DB_PASSWORD, database: process.env.DB_NAME};
console.log('Database configured for:', dbConfig.host);Important: Never Commit .env File!
Add `.env` to your `.gitignore` file so it never gets committed to your repository.
# .gitignore.envnode_modules/Example: Database Connection with Environment Variables
require('dotenv').config();const mysql = require('mysql2/promise');
const pool = mysql.createPool({ host: process.env.DB_HOST, user: process.env.DB_USER, password: process.env.DB_PASSWORD, database: process.env.DB_NAME, waitForConnections: true, connectionLimit: 10});
async function queryUsers() { try { const [rows] = await pool.query('SELECT * FROM users'); console.log(rows); } catch (err) { console.error(err); }}Best Practices
- Use environment variables for all configuration.
- Provide a `.env.example` file in your repository (with dummy values).
- Load dotenv at the very beginning of your app.
- Use `||` to provide sensible defaults when possible.
- Never commit real secrets to version control.
Two Minute Drill
- Environment variables keep configuration out of your code.
- Access them via `process.env.VARIABLE_NAME`.
- Use `dotenv` to load variables from a `.env` file.
- Never commit `.env` – add it to `.gitignore`.
- Provide a `.env.example` with sample values.
- Essential for database passwords, API keys, and port configuration.
Need more clarification?
Drop us an email at career@quipoinfotech.com
