Environment variables are used to store configuration values like API keys, database credentials, and ports outside your code. This makes your app more secure and flexible across different environments (development, testing, production).
Keep sensitive data out of the source code
Easily switch configuration for different environments
Prevent accidental exposure of secrets in version control
Common examples:
.env FilesInstall dotenv package:
Create a .env file in the root of your project:
Load environment variables in app.js:
process.env.VARIABLE_NAME is used to access variables
|| provides a default value if variable is missing
Keeps credentials secure and flexible
Avoid hardcoding secret keys
Easier to rotate keys in production
Do not commit .env to Git – add it to .gitignore.
Use different .env files for development, testing, and production.
Keep sensitive credentials outside source code.
Access variables via process.env.VARIABLE_NAME only.
Consider dotenv-safe or dotenv-expand for more advanced validation.
.env → Stores environment variables
app.js → Uses dotenv to load variables
Keeps configuration clean and secure
Environment variables are essential for real-world Express apps, especially when dealing with databases, authentication, and third-party services.
Take quizzes related to this topic and see where you stand!
Start Quiz Now