Skip to main content

Environment Variables

What is Environment Variable

Environment variables are values that can be passed to an application at runtime to configure certain aspects of the application's behavior. They are a set of dynamic named values that can affect the way running processes will behave on a computer. They are part of the environment in which a process runs.

Use cases

Environment variables are useful for storing sensitive information such as database credentials, API keys, and other configuration settings. They are also useful for storing configuration settings that are specific to the environment in which the application is running, such as the port that the application should listen on. This allows you to have one codebase that can be used in different environments (development, staging, production, etc.) without having to change the code. You can simply change the environment variables to configure the application for the environment it is running in. To change the environment variables you don't need to change the code, you just need to change the environment variables in the environment in which the application is running. Environment variables are outside the application code, so they can be changed without having to redeploy the application.

What's the environment, and types

Environment means the environment in which the application is running. Each environment has its own set of environment variables having different values, like database credentials, API keys, etc.

There are normally three types of environments:

Sometimes even more environments are used, such as a testing environment, QA environment, etc for testing purposes. But the most common environments are development, staging, and production.

Development Environment

The development environment is the environment in which you develop your application. In this environment, the application runs locally on your computer. You can also run the application on a server that is accessible only to you. This environment is used for development purposes only. It is not accessible to the public.

Staging Environment

The staging environment is the environment in which you test your application before deploying it to production. In this environment, the application runs on a server. This environment is used for testing purposes only. It is not accessible to the public.

Production Environment

The production environment is the environment in which you deploy your application. In this environment, the application runs on a server that is accessible to the public. This environment is used for production purposes only. It is accessible to the public.

Difference between development, staging, and production environment

The difference between development, staging, and production environments is that the development environment is used for development purposes only, the staging environment is used for testing purposes only, and the production environment is used for production purposes only.

Need for separate environment

We already know that environment variables are useful for storing sensitive information such as database credentials, API keys, and other configuration settings. They are also useful for storing configuration settings that are specific to the environment in which the application is running, such as the port that the application should listen on. This allows you to have one codebase that can be used in different environments (development, staging, production, etc.) without having to change the code. You can simply change the environment variables to configure the application for the environment it is running in.

Using separate environment variables for different environments, such as development, staging, and production, allows you to configure your application in a way that is appropriate for each environment. This helps to ensure that your application behaves correctly and is secure in each environment.

Here are a few examples of why you might use separate environment variables for different environments:

  • Development: During development, you may want to use a different database or set of credentials for testing purposes. For example, you could use a local instance of a database for development, with a different set of credentials than the production database. This allows you to test your application without making changes to the production data.

  • Staging: When preparing to deploy your application to production, you may want to test it in a staging environment that is as similar to production as possible. In this case, you would use environment variables that match the production environment, such as the production database URL and credentials, to ensure that the application behaves correctly in the production environment.

  • Production: In a production environment, you want to ensure that your application is as secure as possible. This may include using different credentials for services such as databases, or disabling certain features that are used for development and testing. For example, you might use a different set of API keys for production to limit access to the production data.

It is also possible to use different environment variables for different deployment environments or instances, for example, a different set of credentials for different regions, or for different clients.

Let's code

Let's assume that we have a Node.js application that uses a database, more specifically MongoDB. We want to set the database connection string as an environment variable. We can do this by setting the MONGO_URI environment variable to the connection string. We can then access this environment variable in our application using process.env.MONGO_URI. The process.env object is a global object that contains all the environment variables as properties. The MONGO_URI property will contain the value of the MONGO_URI environment variable.

I am going to use this code which we did in file upload using multer, and the only change I am going to do is to set the database connection string as an environment variable, which previously we were hardcoding in the code.

Install dotenv

First, we need to install the dotenv library, which is a zero-dependency module that loads environment variables from a .env file into process.env.

npm install dotenv

Create a .env file

Then, we need to create a .env file in the root folder of the project and set the MONGO_URI environment variable to the database connection string.

.env
MONGO_URI=mongodb://localhost:27017/learning-express-js
PORT=3000

Import dotenv and call the config() method

Need to import the dotenv library in the entry point of the application, which would be index.js in our case.

Import dotenv and call config()
import dotenv from "dotenv";

dotenv.config();
note

By default, the dotenv library will look for a file named .env in the root folder of the project. If you want to use a different file name, pass the file name as an argument to the config() method. For example:

Configuring dotenv to use a different file name
dotenv.config({ path: "./config/config.env" });

This will look for a file named config.env in the config folder of the project.

Note that the path option is relative to the root folder of the project, so you don't need to specify the full path.

Use process.env.MONGO_URI instead of the hard coding value

Then, we need to change the database connection string from hard coding to process.env.MONGO_URI which will get the value from the MONGO_URI environment variable.

process.env

The process.env object is a global object that contains all the environment variables as properties. You can access the value of an environment variable using process.env.VARIABLE_NAME.

Using process.env.MONGO_URI instead of hard coding value
mongoose.connect(process.env.MONGO_URI);

Now, we can run the application, and it will connect to the database using the database connection string from the MONGO_URI environment variable.

tip

Sometimes, to avoid any crashes due to the unavailability of certain environment variables, we can set default values. For example, if the MONGO_URI environment variable is not set, then we can set the default value to mongodb://localhost:27017/learning-express-js. We can do this by using the || operator.

Using default values for environment variables
mongoose.connect(
process.env.MONGO_URI || "mongodb://localhost:27017/learning-express-js",
{
useNewUrlParser: true,
useUnifiedTopology: true,
},
);

Complete code

index.js
import express from "express";
import mongoose from "mongoose";
import dotenv from "dotenv";

dotenv.config();
const app = express();
app.use(express.json());

mongoose.connect(process.env.MONGO_URI);

const port = process.env.PORT || 3000;
// If the PORT environment variable is not set, then use 3000 as the default port

app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});

Code

You can find the code for this doc from here