NodeJS/Express projects

When you develop a NodeJS project, you will most commonly have multiple environments and usually follow a flow akin to this one:

  1. You develop new features on your development environment

  2. You push the changes to a remote server (staging, pre-prod, sandbox, ...) with a similar configuration to your production environment

  3. You deliver the feature to your users in production

Setting up environment variables allow you for example to integrate third party services with API keys, identify the current environment to activate or deactivate some features, provide informations to your context, connect to the right database. This is a mandatory step to ensure scalability and to scope features from environment to environment. At Forest Admin, we do use this kind of app contextualisation to identify your environments, perform authentication on your servers and much more. Setting up such a context is mandatory to integrate Forest Admin to your project, and this document will explain how to setup environment variables.

Install Dotenv in your project

Dotenv is a zero-dependency module that loads environment variables from a .env file into process.env. To install it in your project, simply run the following at the root of your project:

npm install -s dotenv@latest

This will install the dotenv dependency in your project.

Initialise your Dotenv package

The initialisation of dotenv is pretty straightforward. To make it push the variables from your .env into your node environment, simply at the following at the very top of the entry script of your node application (most commonly app.js).

Do note that if the Dotenv package is not initialized before requiring forest packages, they might initialize themselves with wrong environment variables. Require the Dotenv configuration before anything else.

app.js
require('dotenv').config()
...

Configure your environment variables

Create a .env file at the root of your project, and add in your environment variables. Forest Admin environment variables will look like the following:

.env
APPLICATION_URL=http://localhost:3310
FOREST_AUTH_SECRET=fad0c3f44629c1892a0da65e957ac4ef8eb20f3dfbb4d861f032864062933a7c0b3c479ee42c0907179d2a3dafeaafb2
FOREST_ENV_SECRET=03940b538e6a7b58dd07754f40dcdf63edc03acd295d593e1746fad5dc6e8958

And that's it! You can now restart your server, and your environment variables will be automatically handled by dotenv.

Please keep in mind that every-time you change your environment variables, you need to restart your server so the changes will be applied.

If you have versioned your code, consider adding the .env file to your ignored files from git, in .gitignore

Last updated