Environment Variables and Configuration in Node.js
Environment Variables and Configuration in Node.js – Complete Beginner Guide
Environment variables in Node.js are used to store configuration values outside your code. They help you manage sensitive data like API keys, database URLs, and secret keys securely. Using environment variables is a best practice in backend development.
What are Environment Variables in Node.js
Environment variables are key-value pairs stored outside your application. They are accessed in Node.js using process.env. This allows you to change configuration without modifying your code.
Why Use Environment Variables
Environment variables improve security. They keep sensitive data like passwords and API keys hidden. They also make your application flexible across different environments like development, testing, and production.
Accessing Environment Variables
You can access any environment variable using process.env.VARIABLE_NAME.
Setting Environment Variables
In your system or terminal, you can define variables.
SECRET_KEY=mysecret
Using dotenv Package
The dotenv package helps you manage environment variables easily using a .env file.
Create a .env file
DB_URL=mongodb://localhost:27017/mydb
SECRET_KEY=mysecret
Load dotenv in your app
console.log(process.env.DB_URL);
Using Environment Variables in App
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
Configuration for Different Environments
You can use different configurations for development and production.
Example:
Development uses local database
Production uses cloud database
Best Practices for Environment Variables
Do not store .env file in Git
Use strong secret keys
Use different values for each environment
Validate required variables at startup
Keep variable names clear
Common Use Cases
Database connection strings
JWT secret keys
API keys
Server port configuration
Real-World Example
In a Node.js API, you store DB_URL and JWT_SECRET in environment variables instead of writing them in code. This keeps your app secure and flexible.
Internal Link
Click here for more free courses
FAQs
What are environment variables in Node.js
They are values stored outside code for configuration.
Why use dotenv
It helps manage environment variables using a .env file.
Is it safe to store secrets in .env
Yes, if the file is not shared publicly.
What is process.env
It is used to access environment variables in Node.js.



