Learn how to configure a Node.js application via environment variables and customize an .env file with new environment variables.
Applications are commonly required to deploy to many different environments, including staging, testing, and production, without building environment-specific artifacts.
Methodologies like the 12 Factor App specify that an application’s code and configuration are separate but combine during deployment to accommodate specific environments.
Environment variables are one of the preferred methods to define and consume environment-specific configuration values because they are supported by all major operating systems.
They can be defined in most cloud-provider Platform as a Service (PaaS) offerings, and are a common method for configuring platforms, like Docker.
However, it is sometimes convenient to define application settings in a local configuration file instead.
For example, when developing and debugging applications locally, especially when working across many feature branches, the ability to define a set of environment variables in a file streamlines a developer’s experience.
.env files provide a popular solution for defining environment variables, particularly in Node.js. Platforms like Heroku, for instance, use
.env files as part of their recommended best practices.
In this post, we’ll look at a simple Node.js application configured via environment variables, and explore how to customize an
.env file with new environment variables that override default values.
We’ll then demonstrate how to use multiple customized
.env files to quickly switch between multiple environment-specific configurations.
The sample application we’ll be working through is available on GitHub. To run the application locally, ensure Node.js is installed.
Alternatively, you can run the application in CodeSandBox. Click the link to open the GitHub
source code in a new sandbox to build, run, and expose via a random URL.
#node #nodejs #web-development #webdev