Node.js Masterclass
High-Performance Backends01.Home02.Introduction03.Environment Setup04.Modules & Exports05.File System (fs)06.Path & OS Modules07.Buffer & Streams08.Events & EventEmitter09.HTTP Module10.NPM & Package.json11.Express.js Fundamentals12.Express Routing13.Express Middleware14.RESTful API Development15.Asynchronous Programming16.Error Handling17.Database with Mongoose18.Authentication with JWT19.Environment Variables20.Testing with Jest21.Deployment & PM2
Environment Variables
Hardcoding sensitive information like API keys, database credentials, or secret keys in your code is a major security risk. Instead, you should use Environment Variables.
1. Using .env files
The dotenv package is the standard tool for loading environment variables from a .env file into process.env.
npm install dotenvCreate a .env file:
PORT=5000
MONGO_URI=mongodb://localhost/mydb
JWT_SECRET=mySuperSecretKey1232. Accessing in Code
Require dotenv as early as possible in your application (usually the very first line of app.js).
require('dotenv').config();
const port = process.env.PORT || 3000;
console.log(`Running on port ${port}`);
const db = process.env.MONGO_URI;3. Security Hierarchy
In production environments (like AWS, Heroku, or Vercel), you don't use .env files. Instead, you set variables directly in the platform's dashboard. Node.js treats these as higher priority than local files.
CRITICAL: Always add
.env to your .gitignore file to ensure your secrets are never pushed to GitHub.4. Best Practices
- Use
process.env.NODE_ENVto check if the app is in 'development' or 'production'. - Group configurations into a
config.jsfile that exports values fromprocess.env.