Seán Behan Seán Behan - 5 months ago 36
Javascript Question

Using dotenv in a Node JS module

I am building a Node app that returns results for a search using a Google Custom Search Engine(CSE).

I am going to separate the part of the app that sends the request to Google and returns the results into a module.

I use dotenv already in the app to store MongoDB credentials and the app's URL.

I also want to use dotenv in the module to store the Google CSE ID and the API key for the CSE.

I want my module to work independently of the main app but also to use the main app's dotenv file when it's a module.

Currently my module structure looks like this:

module
|
+-- node_modules
| |
| \-- dotenv
| |
| \-- (dotenv module's files....)
|
+-- .env
|
\-- index.js


This works perfectly on its own. The .env file stores the required environment variables and I can access them in the index.js file by requiring the dotenv module.

When included in the main app the structure looks like this:

app
|
+-- node_modules
| |
| +-- dotenv
| | |
| | \-- (dotenv module's files....)
| |
| \-- my_google_search_module
| |
| +-- node_modules
| | |
| | +-- dotenv
| | |
| | \-- (dotenv module's files...)
| |
| \-- index.js
|
+-- .env
|
\-- index.js


This also works. I store all the environment variables in the main app's .env file and by requiring dotenv in the app's index.js I can access those variables. Plus, the "my_google_search_module" seems to be pulling its required variables from the .env file in the root of the app. There is no .env file in the module.

My question is am I doing this the right way?

Answer

I have researched this further and can confirm that the module's .env is pulling the required environment variables from the app's .env file.

I believe this section from the dotenv readme, though not exactly related, verifies that - https://www.npmjs.com/package/dotenv#what-happens-to-environment-variables-that-were-already-set

We will never modify any environment variables that have already been set. In particular, if there is a variable in your .env file which collides with one that already exists in your environment, then that variable will be skipped. This behavior allows you to override all .env configurations with a machine-specific environment, although it is not recommended.

Comments