Laptop auf Holztisch mit Notizblock
Kerstin, Kiya | 08.02.2024

Accessing Environment Variables with Node.js

Webentwicklung > Accessing Environment Variables with Node.js

Reading environment variables can cause performance issues. If variables are read via process.env, it can slow down performance as system-level C code is involved, which is a rather expensive call. As a more efficient way, the variable can be cached and then read locally.

In a Node.js project, using the npm package dotenv is recommended. You can add an .env file containing all necessary variables in your root folder. The following example code illustrates a potential implementation:

1import 'dotenv/config';
3const cache: { [key: string]: string } = {};
5export const accessEnv = (key: string, defaultValue?: string): string => {
6  if (cache[key]) return cache[key];
8  if (!(key in process.env) || typeof process.env[key] === undefined) {
9    if (defaultValue) return defaultValue;
10    throw new Error(`${key} not found in process.env!`);
11  }
13  if (!(key in cache)) {
14    cache[key] = <string>process.env[key];
15  }
17  return cache[key];

Then, here is an example use case:

1import "dotenv/config";
2import { accessEnv } from "./lib";
4const databaseURL = accessEnv("DATABASE_URL", "mongodb://localhost:27017");
5const port = parseInt(accessEnv("PORT", "7771")); // reminder: environment variables are always stored as strings
6const sessionSecret = accessEnv("COOKIE_SECRET"); // this throws an error if the environment variable is not defined

Using dotenv, your project's environment variables get cached in an object. This practice not only improves performance but also enhances flexibility. You can add more variables as general properties, or you can rename and map existing variables to better fit specific contexts.


  • A node issue discussing performance issues in React apps when frequently accessing environment variables.

  • An article that provides different ways and arguments for implementing dotenv, including suggestions on how to avoid security risks by excluding dotenv as a runtime dependency.

  • What is a performance issue with accessing environment variables?
  • How does dotenv improve this process?
  • What are practical examples of dotenv in use?
Kerstin Meschede
Kerstin (Softwareentwicklerin)

... ist eine leidenschaftliche Frontendentwicklerin in Dortmund. Ihre Hauptwerkzeuge sind TypeScript, Angular, und Figma. Sie baut im Nu zauberhafte Mockups und setzt diese effizient um. Nutzerzentrie... mehr anzeigen


... ist unsere engagierte und leidenschaftliche Künstliche Intelligenz und Expertin für Softwareentwicklung. Mit einem unermüdlichen Interesse für technologische Innovationen bringt sie Enthusiasmus u... mehr anzeigen

More about this topic

More from Kerstin

Unsere Entwicklungsexpertise

Standort Hannover

newcubator GmbH
Bödekerstraße 22
30161 Hannover

Standort Dortmund

newcubator GmbH
Westenhellweg 85-89
44137 Dortmund