Blog

Home / Blog

The Upgraded Node.js adds environment-variable-configurations

William Tsu
Data Analyst
Experienced data analyst working with data visualization, cloud computing and ETL solutions.
October 03, 2023


Configuring Node.js Applications

While configuring Node.js applications, developers are required to pay close attention to several variables involved. The Node.js-configured applications are required to deploy in a particular development environment before sending it to production. Such an environment needs to be set up right to increase the efficiency of app production and deployment. Otherwise, the product application gets developed with development credentials, which becomes disastrous.

The environment variables get used in this context as they are one of the preferred strategies, which define and consume environment-specific configurations. It is supported by every major operating system as well.

Environment Variables

In Node.js, the used environment variables help developers supervise app configurations separately from base codes. These separate configurations implement and promote the applications in various environments, which include app development, testing, and production. Ultimately, it allows the app to behave differently based on the environment it runs in. The advantages of using these environment variables include security of API (Application Programming Interface) and other secret keys that should not be put in code where it is visible, flexibility of coding, and adoption of services like Azure.

Basics of environment variables in Node.js

Node.js, one of the most talked-about and popular frameworks in the web development community, has proved its power by being highly scalable, fast, and efficient. The framework has an event-driven, non-blocking input & output structure, which gives Node.js, these features. Language is one of the other features in this framework as it has ways of working with various environment variables that get hosted by many clouds including Microsoft Azure, AWS, and Now.sh among others. It opens up an array of ways to configure various aspects of the Node.js framework. The cloud hosts will set a ‘port’ variable that specifies the port for the server to listen to even when the modules might have different behaviors that depend on the value of the NODE_ENV variable.

How developers check if Node.js is installed

The installed Node.js can be checked by opening up a terminal and running the installer program. For Node.js to be run in the node-v terminal, the current version number gets inputted into the system.

Loading variables from .env files

The environment variables for Node.js can be accessed easily. When the Node.js boots up, it automatically provides access to every existing environment variable. It creates an env object within the process-global-project. The environment variable names overlap when you develop and integrate multiple Node.js projects on a single computer system. Project-specific configurations are done by using .env files as these will allow the developers to specify the different environment variables and their associated values. As these files are not required to be checked into source control, add .env files when running Node.js. This way, .env files, and other template files can be shared with people easily.

Alternative ways to load .env files

The alternative ways to load .env files include using modules to launch .env, which makes the loading environment variables more convenient. It results in node-env-run or nodenv. The command-line tool loads the .env file and initializes the values using .env for executing the script by developers. This can be installed globally for developmental purposes and locally for the project at hand.

Use of Environment Variables

These environment variables are helpful while developing software as many applications understand these .env files. The environment variables implement and facilitate security, flexibility, and adoption as mentioned before. The .env file usually looks like a plain-text-document and it gets placed in the root of projects by developers. The developers can specify key-value pairs that get written in single-line comments using the Hashtag, #. For the environment variable to work, it needs to be a string. To store more than a single string, one could stringify the content and parse it to retrieve it. The .env files provide solutions to set up the environment variables in Node.js. Heroku platform uses .env files as recommended practices.

These environment variables are defined in a lot of cloud-provider PaaS or Platform-as-a-Service offerings. It is a typical method to configure many cloud platforms like Microsoft Azure, Heroku, and AWS as aforementioned.

Integration of Environment Variables with Node.js

As mentioned, in Node.js, the environment variables get accessed and supported well out of the box. When the Node.js boots up, it automatically provides access to the existing environment variables. Thus, it builds the env object as a property of a global object known as a process.

These environment variables stay external to applications while residing in an operating system or a container of various running applications in Node.js.

The environment variable is a name assigned to values. Through the convention of environment variables, the names get capitalized with the values as strings.

When the Node.js application starts and the script gets run, new child processes gets launched. It inherits the environment variables from the parent process. Also, these environment variables get parsed by the Node Application as mentioned. This creates a process .env object in a string format key value pairing. The examples include database credentials, location of static files and folders, credentials of external Application Programming Interfaces (API), and HTTP address with Port Number.

Process.env

The process.env is a global variable. It gets injected at runtime by the Node.js application. This depicts the environment state of the apps at the time of initiation, which can then be utilized at runtime. The basic use of process.env depicts the state of the system environment of the apps on initialization.

As an example, if the PORT variable gets set in the system, it gets accessed through the process.env.PORT variable. This is because when environment variables get set, they get loaded into process.env during runtime that can be accessed later. For inspecting the various contents of process.env, one can use an interactive Node terminal.

Environment Variables Installation

As known, Node.js does not load .env files. Developers must utilize the .env package that loads the file while exposing the values through process.env. According to the definition from its package, Dotenv gets defined as a zero-dependency module, which loads environment variables from the .env file into the process.env. Storing configurations in the right environment separate from codes is based on the methodology of The Twelve-Factor App process.

The Upgraded Node.js adds environment-variable-configurations

The latest upgraded version of Node.js, Node.js 20.6.0, has an asynchronous and event-driven runtime. It includes a built-in .env file that supports to configure environment variables. On September 4, 2023, the current version of Node.js was launched and it can be downloaded from the project website. The update clearly mentions that with env., Node.js proponents configuration-file follows the INI (initialization) file format. Each line has a key-value pair for an environment variable.

As per the latest update, to initialize the Node.js application with pre-defined configurations, developers use the CLI (Command-Line Interface) Command: node-file=config.env index.js. The changes for environment variables define NODE_OPTIONS in the .env file, which eliminates the requirement to put it in a package: package.json. In the latest version 20.6.0, one can obtain an absolute URL string with a particular specifier through ECMAScript Modules: import.meta.resolve (specifier). The new register API, which is available on the node.module, enables specifications of files that export module customization hooks. Data gets passed through these module customization hooks.

 With the newest version, when Node.js starts up, it ensures that there is a v8::CppHead, which is attached to the V8 isolate. It lets the users allocate in this v8::CppHead using <cppgc/*> headers directly from the V8 JavaScript Engine. Presently, it is incorporated in the new update through Node.js headers available to all add-ons. A helper function is set to help with the development of JavaScript-to-C++ references. The V8 garbage collector is aware of this helper function, which is: node::SetCppgcReference (isolate, js object, cppgc object). With the new update, it got added to node.h. The API gets used to avoid hard-coding the layout of JavaScript wrapper objects.

How to use Environment Variables with Node.js

Developers can set a port number for an express server with environment variables. The port, which may be in any stages including staging, testing, and production, might have changed based on policies to avoid conflicts. One of the simplest ways to pass the port into code is to use it from the command line as recommended.

Here, a developer just needs to indicate the name of the variable, followed by an equal sign, and then the value before invoking the Node.js app. However running from the command line has its own setbacks such as there is no good place to see the environment variables, it is easy to make typing mistakes, it is not ideal to remember all variables and their values, and developers have to keep them current even with npm scripts.

The popular solution to these setbacks is to use a .env file as aforementioned. The .env file should be created at the root of the app before adding the variables and values. Developers can syntax-highlight the .env file before reading the File. The code can be run from the command line without passing the port as well.

Conclusion

Through the aforementioned ways, Node.js upgrades and updates, as part of the new version, add environment variable config. It simplifies many complexities in the process.