23.3.2022 |

A Handy Utility TypeScript Function To Access Environment Variables

Here is a useful helper function for reading out environment variables. The function puts the environment variables into a cache to improve performance and also makes sure that you can define default values in your code.

In the case that an environment variable is not assigned, you now can fall back to the default value.

If you don't define a fallback value, the function throws an error and can help you save headaches when your program does not run because you forgot to define an environment variable.

I found this utility somewhere, but I unfortunately cannot remember anymore who wrote it originally. Judging from a GitHub search, it seems like many people use this utility.

Why would you want to cache an environment variable?
It looks like accessing process.env repeatedly during the runtime of your program results in slow code, as you repeatedly call the underlying C code.

This example uses the npm package dotenv to load environment variables from a .env file:

import 'dotenv/config';

const cache: { [key: string]: string } = {};

export const accessEnv = (key: string, defaultValue?: string): string => {
  if (cache[key]) return cache[key];

  if (!(key in process.env) || typeof process.env[key] === undefined) {
    if (defaultValue) return defaultValue;
    throw new Error(`${key} not found in process.env!`);

  if (!(key in cache)) {
    cache[key] = <string>process.env[key];

  return cache[key];

Example usage in your code:

import "dotenv/config";
import { accessEnv } from "./lib";

const databaseURL = accessEnv("DATABASE_URL", "mongodb://localhost:27017");
const port = parseInt(accessEnv("PORT", "7771"));
const sessionSecret = accessEnv("COOKIE_SECRET"); // this throws an error if the environment variable is not defined


Zur Übersicht

Mehr vom DevSquad...

Sven Röttering

Factory Methode Pattern

Patrick Beckmann

Learn Git Branching