Access variables from the .env file in a Node.js application?

looper003 asked this question 1 year, 5 months ago
looper003 on Dec 13, 2021

In the root of my Node.js application, I have a .env file that contains some variables like API keys, passwords, etc.

How do I access those variables in the code of my Node.js application?

1 suggested answers
coderguy on Dec 22, 2021

I'd use the dotenv NPM package. It makes things super easy!

Install it to your Node.js application:

npm install dotenv --save

Then, add this code to the entry file for your application (i.e. index.js):

const dotenv = require("dotenv")


Make sure the dotenv.config() line of code is added as early as possible in your application to make sure your code has access to the .env variables.

You should now be able to access the variables in your .env file via the process.env object:


That will work globally across your application.

0 replies