Using Environment Variables In Node.js 20.6.0

With the current release of version 20.6.0, Node.js now has integrated aid for .env files. You can now load environment variables from a .env file into process.env in your Node.js utility completely dependency-unfastened.

Loading an .env file is now as easy as:

node --env-file .env

Node.js 20.6.0; Source: LinkedIn 


What is .env?

.env documents are used to configure environment variables given inside a running utility. The concept comes from the Twelve-Factor App technique, which says to shop the entirety, which will likely differ among deploys (e.g., development, staging, production) in the environment.

Node.js .env; Source: DEV Community


Config must no longer be part of your software code and should no longer be checked into model management. Things like API credentials or other secrets and techniques must be saved one after the other and loaded within the environment in which they're needed. A .env file helps you manage your configuration for applications where setting variables in the environment isn't realistic, like your development device or CI.

There are libraries in lots of different languages that help using a .env file to load variables into the environment; they're normally referred to as “dotenv”, and the Node.js dotenv is the same. But now, Node.js itself supports this behaviour.

How do you use .env in Node.js?

A .env file can look like this:

PASSWORD=supersecret
API_KEY=84de8263ccad4d3dabba0754e3c68b7a
# .env files can have comments too

By convention, you will keep this as .env within the root of your project, although you may call it anything you need.

You can then set the variables inside the file as environment variables by beginning Node.js with the --env-file flag pointing to your .env document. When loaded, the variables are to be had as residents of file.env.

$ node --env-file .env
Welcome to Node.js v20.6.0.
Type ".help" for more information.
> console.log(process.env.PASSWORD)
supersecret
undefined
> console.log(process.env.API_KEY)
84de8263ccad4d3dabba0754e3c68b7a
undefined

Built-in Env Files Support

Let’s do an easy check by putting in the contemporary NodeJS model as of today (September 5, 2023) and using a basic .env file. Feel free to get NodeJS v20.6.0 from the official download web page or by using NVM.

Let’s make sure our current  NodeJS version using the usage of the command node -v or nvm contemporary

Environment variables; Source: YouTube

Now, we install NodeJS v20.6.0 using the command: nvm install 20.6.0

If you have it hooked up already, an easy nvm use of 20.6.0 will do. At the stop, we can affirm the hooked-up model is present by way of the usage of the primary command as illustrated above. We have created a primary environment file with a single line as content material:

ACCESS_KEY=FAKE_ACCESS_KEY

Along with a minimalist index.js file runnable by way of NodeJS, here’s its content material:

console.log("The access key is: ${process.env.ACCESS_KEY}")

Both documents are primary and best used for instance purposes, so we aren’t managing a full-fledged NodeJS mission. However, the concept is the same on account that to get entry to environment variables in NodeJS, you’ll follow the pattern:

process.env.THE_ENVIRONMENT_VAR_KEY.

Then, we can run the project with node --env-file=.env index.js:

The access key is: FAKE_ACCESS_KEY

As you can see, it truly prints the content material of the ACCESS_KEY environment variable with no dependency mounted. If you are using a version lower than 20.6.0, you’ll get the following message since it wasn’t protected in NodeJS: node: bad option: --env-file=.env

Supported features

Support proper now within reason, which is fundamental compared to dotenv. For example:

  • You can not presently use multiline values
  • You can not use variable growth
  • You can handiest specify one file at a time. Node.js will most effectively use the closing flag surpassed, so within the following instance, the variables from .env.Development could be used: node --env-file .env --env-file .env.development

More work must be done, and some of these features may be added.

There is more work to be accomplished, and many of these capabilities can be added.

Incorrect features

As of the 20.6.0 launch, the documentation says, “If the equal variable is defined inside the environment and the document, the value from the environment takes priority.” This is the way that every dotenv program works by default. However, that is not currently authentic for Node.js’s implementation, and variables inside the .env file will override the environment.

Benefits of Node.js’s Implementation

Even though this implementation lacks some functions, it has some benefits over using a third-party bundle. Node.js hundreds and parses the .env file as it takes off, so you can include environment variables that configure Node.js itself, like NODE_OPTIONS.

So, you could have an .env file that looks like this:

NODE_OPTIONS="--no-warnings --inspect=127.0.0.1:9229"

Then, when you run node --env-file=.env, the method will run without emitting warnings, and it will activate the inspector at the IP address 127.0.0.1:9229.

Note: You can't position NODE_OPTIONS="--env-file .env to your .env file. It is not allowed to avoid infinite loops.

Why Is This Important?

Simplified Workflow

This exchange simplifies the developer's experience by natively incorporating a custom standard in Node.js development.

Less Dependence on External Packages

By incorporating this option into the middle, Node.js reduces the variety of third-birthday celebration programs that builders want to be familiar with, making it less complicated to get it running.

Unified Configuration

This feature additionally encourages a more unified method of configuration, bringing environment variables and Node options right into a single, easily doable file.

Node.js replacement for dotenv

The dotenv package deal is currently the most famous way to load environment variables from a .env file inside the Node.js environment. From now on, you may not want it anymore. Node v20.6.0 comes with native support for .env configuration files.

Node.js .env; Source: ITNEXTA


A garage mechanism for key/value vars is accessible, but we can also configure the runtime via NODE_OPTIONS. This approach is much less difficult to control than long scripts in the package deal.json file.

Here is a simple instance of invoking a node script with the new --env-file flag.

# config.env
NODE_OPTIONS='--title="Testing Node v20.6.0"'
USER_NAME='Harry Potter'
// index.js
console.log(process.title);
console.log(`Hi ${process.env.USER_NAME} `);
node --env-file=config.env index.js
Testing Node v20.6.0
Hi Harry Potter

Node.js just keeps improving

Go try out Node.js version 20.6.0. Version 20 has delivered new features, like a solid test runner, mock timers, and now .env document assist, as well as many enhancements, fixes, and enhancements. Version 20 will become the active LTS model of Node.js in October, so now is a good time to test these new features and consider upgrading your utility to take advantage of them.

A long-awaited characteristic among NodeJS developers. Finally, beginning with Node.js v20.6.0, Node.js helps .env files for configuring environment variables.

Conclusion

While Node.js 20.6 has streamlined environment variable control with its built-in .env help, it is essential to observe that this feature doesn't extend to React and React Native. These frameworks don't use the Node.js runtime in production and feature their constructor methods and runtimes. As a result, builders may also still want to depend on present methods for environment variable control. For example, legacy React projects often employ equipment like create-react-app, which handles .env files in its way, while React Native builders may turn to libraries together with react-native-config. Any newer projects would use Vite, Astro, or something similar that has integrated help.

Node.js v20.6's addition of integrated .env file aid is more than just a convenience function; it's a strategic move to hold its competitive position in a panorama increasingly motivated by inexperienced people. These emerging technologies have greatly emphasised developer experience right out of the box, pushing Node.js to conform and include such upgrades natively. This replacement isn't just about streamlining utility development in Node.js; it's also about responding to the challenges and placing the bar excessively high in a swiftly evolving environment.



How much is a great User Experience worth to you?


Browsee helps you understand your user's behaviour on your site. It's the next best thing to talking to them.

Browsee Product