An environment variable is a value set outside of a program, usually by the operating system or a service. It consists of a name and a value, and multiple environment variables can be created and accessed by the program.
Here a "service" refers to a system or application that runs in the background on an operating system. These services can set and manage environment variables for the applications they run. for example Services like web servers (Apache, Nginx), container platforms (Docker), and CI/CD tools (Jenkins, GitHub Actions) set environment variables for applications they manage.
Purpose of Environment Variables
The primary use case for environment variables is to limit the need to modify and re-release an application due to changes in configuration data.
Modifying and releasing application code is relatively complicated and increases the risk of introducing undesirable side effects into production.
Environment variables are often used to store data that doesn't change often but is essential for your application to run correctly. Examples include:
The mode the app is running in (like production, development, or staging).
Domain names and API endpoints.
Public and private keys for authentication (secured on the server).
Email addresses for groups like marketing or support.
Names of service accounts.
These values are treated like constants in your code, meaning they rarely change and aren't modified during the application's execution.
Use case in Web development
In web development, environment variables are used to manage configuration settings, such as API keys, database URLs, or environment-specific settings, without hardcoding them into your application. This helps keep sensitive information secure and makes it easier to manage different environments (development, staging, production).
Example: Using Environment Variables in Node.js
Setting Environment Variables:
In a .env
file (not included in version control), you can define your environment variables
PORT=3000
DATABASE_URL=mongodb://localhost:27017/myapp
API_KEY=your-api-key-here
Accessing Environment Variables in Code:
Use a package like
dotenv
to load these variables into your Node.js application.Install the
dotenv
package: npm install dotenv
In your Node.js application, load and use the environment variables:
import dotenv from 'dotenv';
import express from 'express';
const app = express();
dotenv.config();
const port = process.env.PORT || 3000;
const databaseUrl = process.env.DATABASE_URL;
const apiKey = process.env.API_KEY;
app.get('/', (req, res) => {
res.send('Environment variables in action!');
});
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
console.log(`Connected to database at ${databaseUrl}`);
console.log(`Using API key: ${apiKey}`);
});
Explanation
Security: Sensitive information like API keys or database credentials are kept out of your source code.
Environment-specific Configuration: Easily switch between different configurations for development, staging, and production by changing the environment variables without modifying the code.
Code Flexibility: Your code can behave differently depending on the environment (e.g., logging level, API endpoints).
How it Works
The
.env
file defines the environment variables.The
dotenv
package loads these variables intoprocess.env
, making them accessible in your application.process.env.VARIABLE_NAME
retrieves the value of an environment variable, allowing your application to use different settings based on the environment.
It's important not to push your .env
file to GitHub or any version control system. Ensure your .env
file is listed in your .gitignore
file, so Git ignores it when tracking files.
Set environment variables directly in your deployment environment (e.g., in hosting platforms like Heroku, Vercel, or using CI/CD tools). This way, your sensitive data is never included in your codebase.
Environment Variables in Windows OS
In Windows, different programs and processes often need specific settings or environments to run properly. To manage this, Windows stores information about these requirements in various locations, making it easy for the system to retrieve and use them when needed.
In Windows, environment variables are key-value pairs that store configuration information for the operating system and applications.
Environment variables help control the behavior of the system and applications, such as where to find executables or how applications should run.
In Windows, environment variables are categorized into two main types: system environment variables and user environment variables.
System Environment Variables:
These are settings that apply to the entire system, affecting all users and processes on the computer.
They are set by the operating system or administrators and include important configurations like the
PATH
variable, which tells the system where to find executable files.Examples:
PATH
,SystemRoot
,ProgramFiles
.
User Environment Variables:
These variables are specific to a particular user account. They only affect the processes run by that user.
Users can customize these variables without affecting other users on the same system.
Examples:
TEMP
,USERPROFILE
,APPDATA
.
Example:
System Environment Variable:
PATH
: A list of directories where executable files are located. All users on the system can access these paths.
User Environment Variable:
USERPROFILE
: Points to the user’s profile directory, likeC:\Users\YourName
, and is unique to each user.
Using environment variables helps you keep your app easy to configure by separating settings that don't change often from your code. However, how you use them can depend on whether your app is frontend or backend, and where it's running, like on an operating system or in a microservice.