How To Set Environment Variables In Node.js

How To Read and Set Environment Variables In Node.js

Do you have a problem understanding how to set an environment variable in Nodejs? This guide was written to help you with that.

To build secure and robust applications, you must understand environmental variables and how to set them up properly.

Many junior developers hardcode private data like API keys, database passwords, and sensitive information into their codebase. Then they commit and push sensitive data to a version control system which can lead to a security breach.

In this article, I’ll show you how to correctly set up, read, and store an environment variable in Nodejs. 

What you’ll learn here will help you build more secure and flexible applications. Also, it increases your chances of getting a better job, as questions about environment variables are common in interviews.

Let’s dive right in.

What is an Environment variable?

An environment variable is a dynamic value that affects the behavior of a  running process or program in a computer. It is a dynamic value because it can be used and changed by the user, running process, or operating systems.

When building a web app with Nodejs, there are some values and configurations you should not hardcode into your codebase. Some of these include API keys, system paths, configuration settings, credentials, database passwords, and many more.

Hardcoded values make building applications that can adapt to different environments and configurations difficult. You can configure your application with environment variables for different environments, such as development, testing, and production. 

By setting different environmental variables for each environment, you can ensure that your application behaves correctly in each environment.

When to use environment variables in NodeJs

Environment variables are not used to store all the variables you will be using in your application. 

However, they are useful for storing a wide range of configuration settings, such as:

Database connection strings, API keys and secret tokens, Usernames and passwords, URLs and other external service endpoints, Paths to important files or directories and other application-specific settings.

Using environmental variables to store these configuration settings makes your application more flexible, easier to manage, and more secure.

How to set environment variables in Windows

Suppose you are working with the Windows OS. It’s easy to set up environment variables that you can use for your project. You don’t need to know how to use the terminal or shell to do this.

To set an environment variable in Windows, you can follow these 6 easy steps.

  1. Open the Start Menu and search for “Environment Variables.”
  2. Click on “Edit the system environment variables.”
  3. Click on the “Environment Variables” button.
  4. Under “System Variables”, click “New.”
  5. Enter the name of the environmental variable you want to create and its value.
  6. Click “OK” to save the environmental variable.

For example, let’s assume you want to create an environment variable to store the password for a project’s database, `Store` You can use the variable `STORE_DB_PASSWORD` and the value `mysecretkey`.

Check out this video on how to set up an environment variable in Windows 10.

How to set environment variables in macOS and Linux

Setting an environment variable in Linux and macOS is different from Widows. However, it is also an easy task to do.

To set environment variables for Ubuntu Linux, macOS, or any Linux distro. Here is what you should do:

  1. Open Terminal.
  2. Type export VARIABLE_NAME=value and press enter.
  3. Repeat this for each environmental variable you want to create.

For example, let’s say you want to create a global variable for your API key. You could name the variable “API_KEY” and set the value to your API key.

How to Set and Store Environment Variables In Node.js with Dotenv

The dotenv module allows you to load from a `.env` file into the `process.env`. This makes managing your configuration settings and variables directly from your codebase easy. 

However, you should be careful when you commit and push your code to a remote repository. More on that later.

You set and store environment variables with Nodejs. You can follow these easy steps to do t like a pro.

  1. Install the `dotenv` module with npm.

-> npm install dotenv

      2. Create a .env file in the root directory of your project.

  1. Add your environment variables to the .env file in the following format: VARIABLE_NAME=value. 

For example: Suppose you are trying to store your API key as an environment variable; you can write it in this format into your .env file.

API_KEY=sk-akdkakdhirhe340u0943qefh93h393

It is important to note that when storing an environment variable, no space is required before and after the ‘=’ . 

Now that we know how to load and set environment variables in our local computer and using dotenv. 

Let’s learn how to read out variables into our code.

How to read and overwrite environment variables in Node.js

To read and overwrite an environment variable in nodeJs. We use the` process.env` object.

In Node.js, a process.env object is a global object that gives access to the environmental variables that are available to your application. 

Environment variables are key-value pairs. They contain information about the runtime environment in which your application is running.

The process.env object is populated by Node.js with environmental variables by default. These may include variables like PATH and USER, which contain information about the user’s operating system environment.

Here are a few key things to keep in mind when working with the process.env object in Node.js:

To read an environmental variable in your Node.js application. You can use the syntax process.env.VARIABLE_NAME, where VARIABLE_NAME is the name of the environmental variable that you want to access. 

From our previous examples, if you have an environmental variable named API_KEY, you can access its value using process.env.API_KEY.

const password = process.env.STORE_DB_PASSWORD

How To Access an environment variable with NodeJs with dotenv

To access your environment variables with the ‘dotenv’ module. Let’s assume you have the dotenv module installed. You can scroll up a little to see how to do that.

Then in your code base. You follow these steps:

  1. Import the dotenv module
require ('dotenv').config()
  1. Access your environmental variables using process.env. 

For example:

const dbPassword = process.env.DB_PASSWORD
const apiKey = process.env.API_KEY

Using Dotenv to store your environmental variables, you can ensure that your configuration settings are separated from your code and that your application uses the correct settings in each environment.

Best Practices to Set Environmental Variables

When setting environmental variables in Node.js, following best practices is important. Here are a few tips:

  1. Use descriptive names for your environmental variables.
  2. Use uppercase letters for your environmental variable names to make them stand out.
  3. Store sensitive information in environmental variables, such as passwords and API keys.
  4. Do not store sensitive information in plain text in your code or in your version control system.
  5. Use a .env file to store your environmental variables in development environments.

By following these best practices, you can ensure that your environmental variables are easy to manage and secure.

Security Considerations When using environment variables

When setting environmental variables in Node.js, it’s important to consider security. Here are a few tips:

  1. Do not store sensitive information in plain text in your code or in your version control system.
  2. Use a .env file to store your environmental variables in development environments, and do not commit this file to your version control system.
  3. Use a key management system like AWS KMS to manage and protect sensitive information stored in environmental variables.

By following these security considerations, you can ensure that your environmental variables are protected from unauthorized access.

Conclusion

Now that you’ve learned how to read and set environment variables in Nodejs, windows, and macOS. It is important to note that environment variables are one of the basic building blocks to building flexible and secure apps.

Also, never forget to follow the best practices when creating a dotenv file. You should not push your .env file to GitHub or any other public repository.

You can check out other articles on NodeJs,