Dotenv Typescript: The Basics and a Quick Tutorial

Dotenv Typescript Blog Banner

What Are Environment Variables? 

Environment variables are key-value pairs that affect the behavior of running processes on a computer. They are used to store configuration settings and system information that can be accessed by software applications. 

Environment variables may hold data such as database connection strings, file paths, or API keys, allowing for dynamic changes to the application’s runtime environment without altering code. This makes it possible to separate configuration from code—one common use is to allow the same application codebase to run differently across development, testing, and production environments.

This is part of a series of articles about Dotenv.

The Importance of Environment Variables in a TypeScript Project 

In a TypeScript project, environment variables are crucial for managing project-specific settings and sensitive data. They allow developers to configure applications without hard-coding values, maintaining the security of API keys, database connection URLs, etc. 

Environment variables also enhance the portability and scalability of TypeScript applications. Developers can easily adjust the application’s behavior across different environments. This simplifies deployment processes and creates a development workflow that accommodates different configurations.

Note: Environment variables are more secure than storing secrets as part of your codebase. However, they are not encrypted and can be viewed by anyone with access to your runtime environment. Therefore, it’s a best practice to use more secure systems like secrets management solutions for credentials and other sensitive data.

Tips From Expert

In my experience, here are tips that can help you better manage environment variables using Dotenv in TypeScript:

  1. Define types for env variables: Use TypeScript interfaces to ensure type safety for environment variables.
  2. Set fallback values: Provide default values with process.env.VARIABLE || 'default' to prevent crashes if variables are missing.
  3. Use dotenv-safe: Validate required environment variables are defined by using dotenv-safe to avoid missing values in production.
  4. Avoid hardcoded strings: Store keys like REACT_APP_MY_DB_URL in a constants file to prevent typos.
  5. Securely manage production variables: Use environment-specific .env files and secrets management for sensitive data in production.
 
Ran Cohen photo
Ran Cohen
CTO & Co-Founder. Configu
Before co-founding Configu, Ran was a full stack developer at Testim.io and previously served in an elite cybersecurity unit in the Israeli Defense Forces.

What Is the Dotenv library? 

The Dotenv library, available via npm, is a lightweight, zero-dependency module designed to load environment variables from a .env file into process.env in Node.js applications. 

Dotenv simplifies the process of working with environment variables by automatically parsing the contents of a .env file and making the defined variables available within the application’s runtime environment. This setup enhances security, flexibility, and maintainability. 

The library supports both CommonJS and ES6 module imports, making it versatile for various JavaScript and TypeScript projects.

Quick Tutorial: Using Environment Variables in TypeScript with Dotenv

Here’s an overview of the steps involved in configuring environment variables in a TypeScript project using the dotenv library.

Install the Required Packages 

Start by setting up your development environment with the necessary packages. Open a terminal, navigate to your project’s root directory, and execute the following command using npm, Node.js’s package manager:

npm install dotenv ts-node

This command installs two key packages: dotenv and ts-node. dotenv is essential for loading environment variables from a .env file into process.env, making them accessible throughout your application. ts-node allows you to run TypeScript files directly without pre-compiling them to JavaScript, streamlining the development process. 

Configure Your Environment Variables 

To configure environment variables in your TypeScript project, create a .env file at the root of your project directory. This file should contain all the necessary environment variables in key-value pairs. For example, to store an API key, your .env file would look something like this:

REACT_APP_MY_API_KEY=your-api-key-here

Next, add the .env file to your .gitignore to prevent it from being uploaded to version control systems, safeguarding your confidential data.

After setting up the .env file, these variables are loaded into process.env, making them accessible throughout your TypeScript application. 

Create a TypeScript File 

The next step is to create a TypeScript file where you will use these variables. Let’s create a file named app.ts in your project. This file will serve as an entry point for demonstrating how to access and utilize environment variables within your TypeScript code.

// app.ts
import dotenv from 'dotenv';
dotenv.config(); // 

The dotenv.config() function call reads your .env file, parses the contents, and loads them into process.env, making your environment variables available throughout your application. With this setup, you can now access any defined variable using process.env.VARIABLE_NAME, where VARIABLE_NAME is the key of one of your environment variables. 

Import the Environment Variables and Use Them 

In the app.ts file, after configuring dotenv to load the environment variables, you can access these variables directly using process.env. For example, to retrieve a database connection string defined in your .env file, you would write:

const apiKey = process.env.REACT_APP_MY_DB_URL; // Access the database connection string from environment variables
console.log(‘Database URL:', dbUrl); // Output the database URL to the console

This code snippet demonstrates how to fetch and utilize an environment variable within your TypeScript application. By assigning the value of process.env.REACT_APP_MY_DB_URL to a constant named dbUrl, you can use this variable anywhere in your code. 

Run Your TypeScript Files with ts-node 

To run TypeScript files directly in a development environment, use the ts-node tool to enable execution without manual compilation to JavaScript. This capability is especially useful for rapid development and testing. After setting up your TypeScript file and importing the necessary packages, run the file. 

In the terminal, within your project directory, use the npx ts-node app.ts command. This command executes the app.ts file using ts-node, which compiles TypeScript to JavaScript on-the-fly and runs it in Node.js. This enables you to quickly test changes to your code by directly running TypeScript files.

Related content:

Managing and Securely Storing Environment Variables with Configu

In light of the limitations of Dotenv libraries, you should consider a more robust alternative to managing environment variables. 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

Related Content

Dotenv Rails: Managing Environments Variables in Ruby on Rails

Top 3 Dotenv PHP Libraries and a Quick Tutorial

Dotenv in React with react-dotenv Library: Basics & Quick Tutorial

Dotenv Webpack: The Basics and a Quick Tutorial

Using npm dotenv Package to Manage Node.js Environment Variables

Using Py Dotenv (python-dotenv) Package to Manage Env Variables

Managing Environment Variables With dotenv

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