How to read environment variables from Node.js
Learn how to read and make use of environment variables in a Node.js program
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
That will pass the user
USER_ID as 239482 and the
USER_KEY as foobar. This is suitable for testing, however for production, you will probably be configuring some bash scripts to export variables.
process does not require a "require", it's automatically available.
Here is an example that accesses the
USER_KEY environment variables, which we set in above code.
In the same way you can access any custom environment variable you set.
If you have multiple environment variables in your node project, you can also create an
.env file in the root directory of your project, and then use the dotenv package to load them during runtime.
In your js file
You can also run your js file with
node -r dotenv/config index.js command if you don't want to import the package in your code.