Environment Variables in Express
⏱ Estimated reading time: 2 min
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).
1. Why Use Environment Variables?
-
Keep sensitive data out of the source code
-
Easily switch configuration for different environments
-
Prevent accidental exposure of secrets in version control
Common examples:
2. Using .env Files
-
Install dotenv package:
-
Create a
.envfile in the root of your project:
-
Load environment variables in
app.js:
-
process.env.VARIABLE_NAMEis used to access variables -
||provides a default value if variable is missing
3. Using Environment Variables for Database Configuration
-
Keeps credentials secure and flexible
4. Using Environment Variables for JWT Secret
-
Avoid hardcoding secret keys
-
Easier to rotate keys in production
5. Best Practices
-
Do not commit
.envto Git – add it to.gitignore. -
Use different
.envfiles for development, testing, and production. -
Keep sensitive credentials outside source code.
-
Access variables via
process.env.VARIABLE_NAMEonly. -
Consider dotenv-safe or dotenv-expand for more advanced validation.
6. Example Project Structure
-
.env→ Stores environment variables -
app.js→ Usesdotenvto 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.
Register Now
Share this Post
← Back to Tutorials