How to load .env file data before imports?

271 Views Asked by At

I'm trying to use the dotenv package to load data from a .env file.

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

Unfortunately, some of my other modules need to load data from this when they start, and they throw an error if that data is not found, like this:

import * as dotenv from 'dotenv';
dotenv.config();
console.log('token',process.env.TOKEN);
import client from './client.js';

And in client.js, the first line is this:

if (!process.env.TOKEN) throw new Error(`No TOKEN provided in your .env file!`)

So when I run this, I get this error. I have a feeling the import statements are getting hoisted above dotenv.config() (the console.log isn't getting reached), and so it's running client.js before finishing the main file.

If I import / config dotenv in client.js, then it works fine, but that's not the only file that needs to check for dotenv variables.

I don't understand what I am supposed to do here, or why i even need to call .config() at all. How do I load the .env files before importing anything else, so that all the modules I import have access to those variables immediately?

1

There are 1 best solutions below

1
stackers On

(i figured this out right before posting, but am posting in case someone else has the same issue)

Put the dotenv loading into it's own file, like this:

import * as dotenv from 'dotenv';
dotenv.config();
console.log('Loading dotenv file...');
export default true;

and import that before the other modules:

import dotenvLoad from "./dotenvLoad.js";

and that will force it to run the config line before continuing.