Skip to main content

Storing variables in .env

The module dotenv is a zero dependency module which allows loading of variables from the file .env and which can be accessed in process.env. This in turn allows the storing of configuration in the environment separate from code - a component of the "twelve factor app methodology".

Make sure the package dotenv is installed:

yarn add dotenv

Then require the module and call the .config() method high up in the app processing or immediately.

require('dotenv').config()

The .env file might contain variables such as

HOSTNAME=127.0.0.1
PORT=3000

which are then available in the processing of the app like this:

const hostname = process.env.HOSTNAME
const port = process.env.PORT