"TypeError: Cannot read property 'config' of undefined" in dotenv

Viewed 5653

I'm trying to get access to my .env file via dotenv module, but I'm getting the below error

dotenv.config();
       ^
TypeError: Cannot read property 'config' of undefined

I have dotenv installed in node_modules and package.json, my .env file is in the root folder, and I think everything is written correctly, but it doesn't work for some reason. I have tried reinstalling the module, didn't help

4 Answers

try the following :

require('dotenv').config({path: __dirname + '/.env'})

In Typescript

import * as dotenv from 'dotenv'
dotenv.config({path: __dirname + '/.env'})

Another way to fix this is to enable esModuleInterop in Typescript compiler options.

Open tsconfig.json and add this line:

"esModuleInterop": true,

so you can import it like this:

import hello from 'hello-world';

try this:

 const path = require('path')
 require('dotenv').config({ path: path.resolve(__dirname, '../.env') })

try the following

require('dotenv').config()

Related