Let’s face it, your coding environment plays a major role in how your application operates (pun intended)! Managing environment variables is ever more important in today’s containerized and cloud native applications, be it for defining your database connection string per environment or storing your access keys. Using a .env
file is a common practice for managing these variables and dotenv
presents a simple and zero-dependency way to use this method in your JS code.
The package is extremely simple to use, requiring only one line of code and the .env
file in majority of the use cases. The package expects a .env
file in your project’s root directory and injects the variables in the file into the node’s process.env
object when instantiated as below:
require('dotenv').config()
Let’s take the example of using a database connection string defined as DATABASE_CONN_STRING="test_protocol://test:test@test:5432"
in your .env
file. Post instantiating the config, this would be:
database.connect(process.env.DATABASE_CONN_STRING)
For proper usage of the package, we should make sure that the config is loaded only once and at the earliest step of code execution.
#web-development #javascript #nodejs #software-engineering #software-development