Environment Variables: How to Use Them and 4 Critical Best Practices

Environment Variables

What Are Environment Variables? 

Environment variables are dynamic-named values that can influence the way running processes behave on a computer. They exist in every computer system, and they’re used to make the system aware of certain conditions. They can be created, edited, saved, and deleted, and they can be unique to a specific system, user, or application.

An environment variable is made up of a name/value pair. The name is an identifier that is used to call the value in a variety of functions and programs. The value, on the other hand, is the information associated with the variable. This information can be a directory path, a filename, a computer name, or any other type of data.

Environment variables can change as the conditions in the system change. This can be due to changes made by the user, changes made by installed applications, or changes made by the system itself.

In the first part of this article, we’ll provide practical info on setting and working with environment variables in common operating systems and framework. In the second part, we’ll discuss broader considerations—why you should use environment variables, common use cases, options for storing them, and best practices.

How to Set Environment Variables 

Setting Environment Variables in Windows CMD

To set an environment variable in the Windows Command Prompt (CMD), you’ll use the setx command. The syntax is:

setx variable_name variable_value

For example, if you wanted to create an environment variable named TEST with a value of Hello World, you would type: setx TEST "Hello World"

This will create a new environment variable that persists even after the terminal is closed. However, it’s important to note that any changes made with setx will only take effect in future command prompt windows, not in the current one.

Setting Environment Variables in Windows with Powershell

Windows Powershell, a more powerful alternative to CMD, also allows you to set environment variables. The process is slightly different than with CMD. Instead of setx, you’ll use the $env: prefix. The syntax is:

$env:variable_name="variable_value"

For example, you could create the same TEST variable as before with $env:TEST="Hello World"

In Powershell, the changes take effect immediately in the current session, unlike in CMD. However, these changes are temporary and will not persist after the session is closed.

Learn more in our detailed guide to Powershell set environment variable (coming soon)

Setting Environment Variables in Linux Terminal

Setting environment variables in macOS uses the export command, which is the standard for Unix-based systems. The syntax is: 

export variable_name=variable_value

For example, export TEST="Hello World" creates an environment variable named TEST with a value of Hello World.

In Linux, you can check its value by using the following command:

echo $VARIABLE NAME

Again, these changes are temporary. To make them permanent, you’ll need to add the export command to your shell’s initialization file (often ~/.bashrc for the Bash shell).

Setting Environment Variables in macOS Terminal

Setting environment variables in macOS Terminal is similar to Linux—using the export command. The syntax is: 

export variable_name=variable_value

For example, you could create an environment variable named “TEST” with a value of “Hello World” by entering export TEST="Hello World"

Like in Powershell, these changes are immediate but temporary. To make them permanent, you’ll need to add the export command to your shell’s initialization file (e.g., ~/.bash_profile for Bash or ~/.zshrc for Zsh).

In Ubuntu, you can also store them in ~/.bashrc profile.

Setting Environment Variables Using .env Files

Another common way to set environment variables, especially in a development context, is using .env files. These are plain text files that contain key-value pairs in the format variable_name=variable_value

For example, you might have a .env file that looks like this:

TEST="Hello World"
API_KEY="my-api-key"

To use these variables in your application, you’ll need to load them into your environment. Many programming languages have libraries to help with this. Learn more in the following section.

Python Environment Variables

Python, a high-level, interpreted programming language, widely known for its simplicity and readability, makes it easy to work with environment variables. Environment variables are important for many Python applications, primarily when dealing with server-side or backend development tasks.

In Python, the os module provides a way to use environment variables. This module provides a portable way of using operating system dependent functionalities. You can get the value of any environment variable using os.environ. The following code illustrates how this is done:

Executing this file shows the following output:

If the environment variable is not present, it raises a KeyError. To avoid this, you can use the os.getenv() function, which returns None if the environment variable is not present. You can also set the value of any environment variable using os.environ. If you prefer to manage environment variables using .env files, use the python-dotenv library.

Learn more in our detailed guide to Python environment variables

Node.js Environment Variables

Node.js, a JavaScript runtime built on Chrome’s V8 JavaScript engine, uses environment variables extensively. It has a global object called process.env which has all the environment variables as key-value pairs. Node.js uses environment variables for setting different configurations for different environments.

The following Node.js code shows how to do this:

The output should looks like this:

To set environment variables in Node.js, you can use process.env.YOUR_VARIABLE. You can also use the dotenv module to load variables from an .env file into process.env.

Learn more in our detailed guide to Node environment variables

Next.js Environment Variables

Next.js, a React framework for server-rendered applications, also supports environment variables. Environment variables in Next.js are loaded at build time. The example below shows how this is done:

Next.js provides built-in support for environment variables, which you can add in your .env file. To use these variables in your application, you can use process.env.YOUR_VARIABLE. Next.js automatically embeds these variables into the JavaScript sent to the browser, which you can use in your components.

You can execute this code by issuing the following command:

Test it by accessing the above URL on your browser.

Learn more in our detailed guide to Next js environment variables

Ruby Environment Variables

In Ruby, environment variables can be accessed through the ENV object. This object behaves like a hash, and you can access the values by providing the key as a string. You can also set the environment variables by assigning a value to a key in the ENV object.

The following code example shows how it works:

You can run above using the following code:

Ruby also lets you work with .env files. You can use the dotenv-rails gem or other similar libraries.

Docker Environment Variables

Docker, a popular platform used to develop, ship, and run applications, also uses environment variables, which can help containers adapt their behavior in different environments. 

You can set environment variables in the Dockerfile using the ARG instruction (for built-time variables) or ENV instruction (for runtime variables). You can also set environment variables in a docker-compose.yml file or the docker run -e command.

Learn more in our detailed guide to Docker environment variables

Why Should You Use Environment Variables? 

By now, you may be wondering why you should bother using environment variables. Let’s look at some of the main benefits.

Separation of Code and Configuration

One of the primary benefits of environment variables is the separation of code and configuration. This means that the environment in which the code runs can be configured independently of the code itself. This makes the code more reusable and easier to maintain.

When you separate code and configuration, you make it possible to use the same code in different environments. This is especially useful in multi-environment setups, where you might have a development environment, a testing environment, and a production environment.

In addition, separating code and configuration allows you to change the behavior of your code without having to modify the code itself. This can be especially useful when you need to debug your code or when you need to alter the behavior of your code based on external factors.

Platform and Service Agnosticism

Environment variables also provide platform and service agnosticism. This means that they allow your code to run on different platforms and services without requiring any modifications.

For example, you might write a piece of software that runs on both Windows and Linux. While the underlying code for these two platforms might be very similar, there could be subtle differences in the way they handle certain operations. By using environment variables, you can abstract away these differences and write code that works seamlessly on both platforms.

Similarly, you might have a web application that uses different services in different environments. In a development environment, you might use a local database for testing. In a production environment, you might use a cloud-based database for scalability. By using environment variables, you can switch between these services without changing your code.

Version Control Friendly

Environment variables are version control friendly. This means that they can be easily managed using version control systems like Git.

With environment variables, you can store your configuration data outside of your code. This makes it easy to manage changes to your configuration data. You can easily see when a change was made, who made it, and why it was made. 

However, storing environment variables in version control raises serious security concerns. In production environments, you must have a way to encrypt and manage their content, for example by using secret management or configuration management tools.

Security

In terms of security, environment variables are a double-edged sword. Environment variables are often used to store sensitive information, like passwords and API keys. 

On the one hand, storing this info in environment variables is more secure than storing it in your code. This way, even if your code is compromised (or freely accessible on public repositories), the attacker would need to gain access to the system’s environment to view the variables.

On the other hand, environment variables are typically stored in plaintext. So attackers can still easily view and compromise them. The solution is to use platform-specific environment variable mechanisms (for example, on AWS or Heroku), dedicated secret management systems, or configuration management systems.

Related content: Read our guide to environment testing (coming soon)

Common Use Cases of Environment Variables 

Now that we’ve covered why you should use environment variables, let’s take a look at some common use cases.

Configuration Settings for Software Applications

One of the most common uses of environment variables is to store configuration settings for software applications. These settings can include database connection strings, application settings, and more.

For example, you might have a web application that connects to a database. The connection string for the database could be stored in an environment variable. This would allow you to change the database that the application connects to without changing the application’s code.

Storing Sensitive Information

As mentioned earlier, environment variables are often used to store sensitive information. This includes passwords, API keys, and other sensitive data. As mentioned earlier, this is more secure than storing the data in your code, but still presents serious security concerns. 

System-Related Information

Environment variables can also be used to store system-related information. This can include information about the operating system, the file system, the network, and more.

For example, you might have an application that needs to know the location of a certain directory on the file system. You could store this information in an environment variable. This would allow the application to access the directory without hard-coding its location into the application’s code.

Software Version Management

Environment variables can be used to manage software versions. This is especially useful in a development environment, where you might be working with multiple versions of a software package.

For example, you might have a development environment where you’re working with multiple versions of Node.js. You could use an environment variable to specify which version of Node.js should be used. This would allow you to switch between versions without changing your code.

Development Environment Configuration

Finally, environment variables can be used to configure development environments. This includes settings for development tools, build processes, testing frameworks, and more.

For example, you might have a development environment that uses a specific build tool. You could use an environment variable to specify the configuration settings for this tool. This would allow you to change the tool’s behavior without changing your code.

Types of Environment Variables 

Here are the main types of environment variables:

System Environment Variables

System environment variables are variables that are defined for the system and are the same for all users. They typically provide the system with necessary information about its environment, like the location of system files. For example, the PATH system environment variable tells the system where to look for executable files.

System environment variables are not only crucial for the proper functioning of the operating system, but they also play a vital role in the execution of various shell scripts and system commands. A good understanding of these variables can help professionals debug system-level issues and optimize system performance.

User Environment Variables

Unlike system environment variables which are system-wide, user environment variables are specific to each user account on the system. These variables can be used to tailor the user environment, influencing the behavior of software for that specific user.

For instance, a user might have an environment variable that sets their preferred text editor or specifies the directory where they keep their documents. By understanding and manipulating these variables, professionals can customize the user experience to meet specific needs and preferences.

Runtime/Process Environment Variables

The third type of environment variables is runtime or process environment variables. These variables are defined and exist for the duration of a process, and they are usually used to configure the runtime environment of applications.

For example, a developer might set environment variables to specify the database connection details for an application at runtime. Understanding these variables can enable professionals to control and customize the runtime behavior of applications dynamically.

Options for Storing Environment Variables and Their Pros and Cons

There are three main options for storing environment variables. Let’s explore each method and its implications.

Using .env Files

The first option we’ll explore is using .env files to store our environment variables. This method involves creating a file, typically named .env, in which we define our variables. This file is then read by our application at runtime, and the variables are made available through the environment.

One of the main benefits of using .env files is simplicity. It’s easy to create and manage these files, and many development tools and frameworks natively support .env files. This makes it a popular choice, especially for smaller projects or for those just starting out with environment variable management.

However, .env files do have their drawbacks. One of the biggest is the risk of accidentally committing the .env file to version control. This can lead to sensitive information being exposed. To mitigate this risk, it’s common practice to add .env to your .gitignore file. Another downside is that .env files are not typically suitable for production environments. This is because they require manual management and do not integrate well with many deployment tools and services.

Using Platform-Native Variable Storage

The second option for storing environment variables is using the native variable storage provided by your platform or service. For example, AWS provides the Systems Manager Parameter Store, Heroku provides Config Vars, and both Docker and Kubernetes provide their own secrets storage mechanism.

The main advantage of using platform-native variable storage is that it’s more secure and scalable than using .env files. These services usually provide features like encryption, access control, and automatic integration with other services on the platform. This can make them a better choice for larger applications or those with more complex security requirements.

However, the downside of platform-native variable storage is that it can be more complex to set up and manage compared to .env files. It may also tie you to a specific platform or service, which can reduce your flexibility if you decide to switch platforms in the future.

Using Secret Managers or Configuration Management Tools

The third option for storing environment variables is using a dedicated secret manager or configuration management tool. Secret managers are tools or services specifically designed for storing and managing sensitive information. Examples include HashiCorp Vault and our very own Configu Configuration-as-Code platform (learn more below).

Secret managers provide a number of benefits. They typically offer strong security features, like encryption and access control, and they often provide additional features like versioning and auditing. This can make them a good choice for applications with high security requirements or those that need to comply with specific regulations.

Configu acts as an orchestrator across your secret manager, feature flag managers, key-value stores, config databases, and more. Learn more about how Configu works in tandem with secret managers such as Hashicorp Vault.

4 Best Practices for Using Environment Variables 

Proficient use of environment variables requires more than just understanding their types and purposes. It also involves adhering to best practices that enhance security, improve readability, and streamline management.

1. Never Commit Sensitive Information

The first rule of thumb is never to commit sensitive information into your version control system without encrypting or otherwise securing it. Environment variables often hold sensitive data such as database credentials, API keys, or encryption keys. This data should not be committed into version control systems like Git to prevent exposure to unauthorized users.

2. Use .gitignore or Similar Mechanisms

To help adhere to the practice above, use mechanisms like .gitignore files that tell version control systems to ignore certain files. This can be particularly helpful in preventing accidental commits of files containing sensitive environment variables.

3. Use Descriptive, Consistent Naming

Use descriptive names for your environment variables, so they clearly indicate their purpose. This can greatly improve the readability and maintainability of your code, making it easier for others (and your future self) to understand.

It’s also crucial to keep the names and structures of your environment variables consistent across different environments (e.g., development, testing, production), to avoid confusion and potential errors. For application-specific variables, using a prefix can be a good practice. This can help you quickly identify the variables related to a specific application and prevent potential clashes with other variables.

4. Use Configuration Tools for Management

Finally, consider using tools for managing environment variables. These tools can make it easier to set, update, and access variables, and they can also provide additional features like encryption for sensitive data. Even more importantly, configuration tools can help you manage environment variables consistently across multiple environments, programming languages, and frameworks.

Managing and Securely Storing Environment Variables with Configu

Configu is a configuration management platform comprised of two main components, the stand-alone Orchestrator, which is open source, and the Cloud, which is a SaaS solution:

Configu Orchestrator

As applications become more dynamic and distributed in microservices architectures, configurations are getting more fragmented. They are saved as raw text that is spread across multiple stores, databases, files, git repositories, and third-party tools (a typical company will have five to ten different stores).

The Configu Orchestrator, which is open-source software, is a powerful standalone tool designed to address this challenge by providing configuration orchestration along with Configuration-as-Code (CaC) approach.

Configu Cloud

Configu Cloud is the most innovative store purpose-built for configurations, including environment variables, secrets, and feature flags. It is built based on the Configu configuration-as-code (CaC) approach and can model configurations and wrap them with unique layers, providing collaboration capabilities, visibility into configuration workflows, and security and compliance standardization.

Unlike legacy tools, which treat configurations as unstructured data or key-value pairs, Configu is leading the way with a Configuration-as-Code approach. By modeling configurations, they are treated as first-class citizens in the developers’ code. This makes our solution more robust and reliable and also enables Configu to provide more capabilities, such as visualization, a testing framework, and security abilities.

Learn more about Configu

Try Configu for free
Painless end-to-end configuration management platform
Get Started for Free