Should I call dotenv in every node JS file?
Asked Answered
O

8

21

I want to work with environment variables. Unfortunately, I am an inexperienced developer and decided very late to implement such a solution in my project.

I'm trying to inject environment variables, located in .env file, to all JS files (not all of them using environment variables, but I thought it would be faster and easier). Currently, I'm using dotenv package but it is obviously working in one file at once.

Should I use dotenv the standard way? Maybe there's a vulnerability I don't know of and that's why it is very unpopular to use environment variables this way.

if (process.env.NODE_ENV !== 'production') {
  require('dotenv').config();
}
Oppugn answered 3/11, 2019 at 21:7 Comment(1)
no, if you're using an entrypoint file as standard. load it early on then required files will see your process.env.* vars just fine. though you shouldn't put it in any condition, else your chicken/egg if .env contains NODE_ENV and forced to set it earlyCrowder
K
33

You don't need to write require('dotenv').config() in every file. Just include this as the top statement in the index.js or the main file that got executed at the very first place when you run your program.

Kaceykachina answered 4/11, 2019 at 16:25 Comment(2)
Could you give an example? What to you call top statement ?Finella
I don't think this works. Other files imported in the main file will be imported before dotenv.config() finishes adding to process.env even if that's that first line in the main file.Ailey
F
18

Like the comment on your file mentioned, you should have an entry point for your ENVs. You don't want to require('dotenv') in every file.

Instead, create a new file (named something like environment.js) that is in the utils or core folder.

require('dotenv').config();

/* eslint no-process-env:0 */
module.exports.default = {

    env: process.env.env,
    url: process.env.url,
    apiUrl: process.env.apiUrl,
    logLevel: process.env.logLevel,

    db: {
        host: process.env.db_host
        port: process.env.db_port
    }
    // Grab everything in you .env file here
}

Then in each of your other files you can include your configs in a nice json object.

const config = require('../utils/environment');

dbConnector(config.db.host, config.db.port);
// blah blah blah
Faxun answered 4/11, 2019 at 7:6 Comment(1)
Look cool, but it seem redundant.Traipse
A
7

You accepted the first comment but it's not the right way/answer. you can include require('dotenv').config() at the very beginning of your entry file (index.js , server.js ..) and you'll get the process.env variables anywhere in your app by just calling process.env.VARIABLE_NAME

Ario answered 13/5, 2021 at 16:33 Comment(3)
does not work for typescriptTrimerous
Doesn't work. Other project files, which the OP is looking for, will not have the env vars.Ailey
This works. but you should be careful not to import or require any file before require dotenv config. otherwise process.env only works in your entry point file of the app. that means index.js or server.js. if you have required dotenv and have called to config file in a separate line be careful to do it before importing or requiring any other file.Fuchsin
W
1

None of the above answers worked for me. However, I did get it working with the following syntax as the first line of my main (index.js) file:

import 'dotenv/config'

Waine answered 5/3 at 4:46 Comment(0)
P
0

Add it to the entry point of you application. Also if you are importing something like a databaseconnect module , and you are using the enviroment variable , make sure you call dotenv.config() before that, will save you so much time.

Penzance answered 28/2 at 11:57 Comment(0)
M
0

In my case, I am using ES6 imports, and fixed the problem by doing the following things:

  1. In the package.json file make sure you add "type": "module" property, in order to enable ES6 modules.
  2. In your main javascript file make sure you add import 'dotenv/config'; at the very top.
  3. Restart the server, now you should be able to use environment variables everywhere with only one import.

Hope I could give you guys a help!

Martica answered 5/3 at 16:6 Comment(0)
A
0

The answer marked as correct provides the right fix to this problem. This example goes on to show how to make it work with ES6 syntax and Typescript enabled.

In your app.ts file update the order to:

import dotenv from 'dotenv';
dotenv.config();

import cookieParser from 'cookie-parser';
import express from 'express';
import mongoose from 'mongoose';
import logger from 'morgan';
import cors from 'cors';
import path from 'path';

This setup ensures environment configuration precedence over module imports.

Asch answered 26/6 at 7:19 Comment(0)
H
-1

In below example, the file /config/db.config.js using some env variable so I need to add the dotenv.config() line before importing the file.

this is index.js file

const express = require('express');
require('dotenv').config();
const dbConfig = require('./config/db.config');

The conclusion is add dotenv config line on the top of the index.js

Hrutkay answered 16/6, 2023 at 9:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.