Environment variable are undefined inside the child/imported file in node/express

Viewed 1184

I am using dotenv package in my node/express project.

I have an root/index file where I am importing different files.

I imported dotenv in index file only. There within index file environment variable are accessible but in the imported file these are not accessible. How can I make it accessible inside other file imported inside indes.js?

Here's a glimpse of my code

index.js

import dotenv from "dotenv";
dotenv.config();
import { sync, getImages, downloadImage } from "./api/controllers/shutterstock";
console.log(process.env.SHUTTERSTOCK_ACCESS_TOKEN); //===>Working gives me the access token

api/controllers/shutterstock.js

console.log(process.env.SHUTTERSTOCK_ACCESS_TOKEN); //===>undefined

This is how my directory structure looks like enter image description here

3 Answers

Your index.js is importing the api/controllers/shutterstock.js, and imports are "hoisted" (all dependencies are evaluated before starting the execution of the importing module), which causes the console.log in the latter to be evaluated before dotenv.config() is executed and has loaded the .env file.

You can work around this in several ways:

  • don't immediately access process.env in the top-level module scope in shutterstock.js, but e.g. only inside the downloadImage function. If you call downloadImage() after the dotenv.config(), it'll work.

  • defer the loading of shutterstock.js until after dotenv got initialised:

    import dotenv from "dotenv";
    dotenv.config();
    const { sync, getImages, downloadImage } = await import("./api/controllers/shutterstock");
    
  • import a module that does the dotenv.config() call before the shutterstock.js module - dependencies are loaded and evaluated in order. Dotenv comes with such a module already:

    import "dotenv/config";
    import { sync, getImages, downloadImage } from "./api/controllers/shutterstock";
    

import { default as dotenv } from "dotenv"; dotenv.config({ path: '../.env' }); This worked for me when other solutions did not, tried the seperate file import, and everything else in this thread, https://github.com/motdotla/dotenv/issues/133 Also tried other stack articles, this one did the trick with a standard node setup with es6 style imports.

Related