Getting environment variables from file or process

Usage no npm install needed!

<script type="module">
  import agilearchitectsEnv from 'https://cdn.skypack.dev/@agilearchitects/env';


Agile Architects AB - ENV

Getting environment variables from file or process

Environment file

An environment contains the environment variables that is to be present during application execution. The file is usually named .env and placed in the root folder of a project.

key-value pairs are seperated with new line and key and values are separated by an equal sign (=). Example


APP_NAME=my cool app

This defines two variables named APP_NAME and TOKEN with the values my cool app and fw8fh23nf set to each of them. An instance of the env-service is used to parse the text to the actual values.

Creating n ENV service instance

Start by creating a new service instance. ./.env is the path to file to read values from.

import { EnvService } from "@agilearchitects/env";
const envService = new EnvService("./.env");

Read environment variables

// script.js

import { EnvService } from "@agilearchitects/env";
const envService = new EnvService("./.env");

console.log("app name: " + envService.get("APP_NAME", ""));
console.log("token: " + envService.get("TOKEN", ""));
console.log("version: " + envService.get("VERSION", "0.0.1"));
console.log("value of foo: " envService.get("FOO", "variable FOO is empty"));

Using the .env file stated above and executing the following script as APP_NAME="Cool new APP" VERSION=2.0 node script.js should print out:

app name: my cool app
token: fw8fh23nf
version: 2.0
value of foo: variable FOO is empty

Notice how APP_NAME is not overwritten as values from the .env file will always be used before process environment variables.

A good use of this lib:

  • Create env variable values in file for local development instead of having to list them each time when executing application, debugging or testing
  • .env file is a good place to store sensitive data that is not part of the repo (password, secret keys, etc.) or data that is not bound the the application itself (urls, paths, etc).
  • Forces the use of fallback values to avoid application crashing on executing because environment variable is missing