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:
You develop new features on your development environment
You push the changes to a remote server (staging, pre-prod, sandbox, ...) with a similar configuration to your production environment
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:
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.
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:
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