. env files are a popular method for managing application configuration outside the application code, often containing sensitive data such as API keys, database credentials, and other configuration settings. These are environment-specific, which means that developers can have it different. (local.env
, dev.env
, prod.env
).
In this blog post, you will learn how to read the content of a .env file and unlock the full potential of this tool.
How to read .env in Node.js
The process
core module of Node.js provides the env
property which hosts all the environment variables that were set at the moment the process was started.
The below code runs app.js
and set USER_ID
and USER_PASSWORD
.
USER_ID=MECAROGADMIN USER_PASSWORD=admin node app.js
That will pass the user USER_ID
as MECAROGADMIN and the USER_PASSWORD
as admin. This is suitable for testing, however for production, you will probably be configuring some bash scripts to export variables.
Note: process does not require a "require", it's automatically available.
Here is an example that accesses the USER_ID
and USER_PASSWORD
environment variables, which we set in above code.
process.env.USER_ID; // "MECAROGADMIN"
process.env.USER_KEY; // "admin"
In the same way you can access any custom environment variable you set.
Node.js 20 introduced experimental support for .env files.
Now, you can use the --env-file
flag to specify an environment file when running your Node.js application. Here's an example .env
file and how to access its variables using process.env
.
# .env file
PORT=8080
SECRET_KEY=mysecretkey
In your js file
process.env.PORT; // "8080"
process.env.SECRET_KEY; // "mysecretkey"
Run app.js
file with environment variables set in .env
file.
node --env-file=.env app.js
This command loads all the environment variables from the .env
file, making them available to the application on process.env
Also, you can pass multiple --env-file
arguments. Subsequent files override pre-existing variables defined in previous files.
node --env-file=.env --env-file=development.env app.js
Note: if the same variable is defined in the environment and in the file, the value from the environment takes precedence.
.env variable is an important tool for professionals developers because it helps separation of concerns, security, portability, scalability, compatibility.
I hope you enjoyed reading this, and I'm curious to hear if this tutorial helped you. Please let me know your thoughts below in the comments. Don't forget to subscribe to my newsletter to avoid missing my upcoming blog posts.
You can also find me here LinkedIn • Twitter • GitHub or Medium