DotEnv with TypeScript


Working with environment variables is a crucial part of development, as it helps secure sensitive information such as URLs and secret keys.
However, using environment variables in a TypeScript environment can sometimes be troublesome. Here's a comprehensive guide to securely manage your secrets using dotenv in a TypeScript project.
Installing DotEnv and it’s types
Run the following commands to install dotenv and its type definitions:
The Problem with Environment Variables in TypeScript
As shown in the image below, TypeScript cannot automatically infer the types of the environment variables we define.
To fix this, we need to extend TypeScript’s types using interface merging, which allows TypeScript to understand that certain environment variables exist.
Interface Merging
The type definition for environment variables exists in:
And looks something like this —
We need to extend it, we need to add custom properties to ProcessEnv. This helps TypeScript recognize all required environment variables in the project.
Create a env.d.ts file in the root of the project and add the following:
This tells TypeScript that, along with existing environment variables like TZ, variables like JWT_SECRET and PORT also exist and are of type string.
Loading ENV Variables
The usual way of loading env variables into out project is: on the top root file
Import dotenv from “dotenv”
dotenv.config()
access variables by doing — process.env.PORT
The problem here is, if these secrets are used across multiple files, TypeScript might prompt you to import dotenv in each of them.
A better approach is to create a config.ts file, load the environment variables once, and export them as constants.
Better Approach: Create a config file
Now, we can access them across our project by importing config!
Accessing these variables
Advantages of this approach!
Provides TypeScript IntelliSense
Keeps the imports centralized in only 1 file
Ensures type safety
Reduces redundancy
Subscribe to my newsletter
Read articles from Mannem Rohith directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Mannem Rohith
Mannem Rohith
I am a Full-stack enthusiast with experience in developing flexible web applications.