Environment Variables in Node.js

27 August 2018

Many web applications have configurable elements to them. For example, if my application communicates with a database, it needs to know certain information (such as the database host, port, password, and so on) to connect to that database.

How should I store the database connection information? I could hard code it into my application's code, but that causes at least two problems.

First, the database credentials would be visible in the codebase, which is a security issue.

Second, it would also reduce the application's flexibility and portability. For example, if I wanted to change my application's host, I'd have to update its codebase with any new database credentials before I could re-deploy it.

Fortunately, you can avoid hard coded config values by using environment variables. Here I'm going to show you how you can use them in Node.js.


Tags: js