Search code examples
node.jstypescriptdotenv

Environment variables only working when dotenv is imported and configured in each file (instead of just in index.ts)


I should only need to do:

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

in the index.js file. But my .env variables only work when I explicitly import and configure dotenv in each file that uses .env variables.

This is my tsconfig.json :

{
  "compilerOptions": {
    "rootDirs": ["src"],
    "baseUrl": "./src",
    "outDir": "dist",
    "lib": ["es2020"],
    "target": "es2020",
    "module": "esnext",
    "moduleResolution": "node",
    "allowJs": true,
    "esModuleInterop": true,
    "types": ["node"]
  },

}

Not sure why, any ideas?

index.ts: enter image description here

connectToDatabase.ts enter image description here

.env enter image description here

enter image description here


Solution

  • Imports are hoisted, so your dotenv.config isn't being called until after the rest of your imports. To make this work with one import/config call, you can put that in a separate file and import that instead:

    // env.ts
    import dotenv from 'dotenv'
    dotenv.config()
    
    // index.ts
    import './env'
    // followed by all your other imports
    

    And in the future, please post your code, not screenshots of your code. It's faster and easier to just copy-paste!