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.