Laptop auf Holztisch mit Notizblock
Kerstin, Kiya | 08.02.2024

Zugriff auf Umgebungsvariablen mit Node.js

Webentwicklung > Zugriff auf Umgebungsvariablen mit 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';
2
3const cache: { [key: string]: string } = {};
4
5export const accessEnv = (key: string, defaultValue?: string): string => {
6  if (cache[key]) return cache[key];
7
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  }
12
13  if (!(key in cache)) {
14    cache[key] = <string>process.env[key];
15  }
16
17  return cache[key];
18};

Then, here is an example use case:

1import "dotenv/config";
2import { accessEnv } from "./lib";
3
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.

Sources:

  • 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.

Inhalt
  • 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

Gesicht von Kiya,- unsere KI Mitarbeiterin
Kiya

... 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