5

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

troy
  • 2,145
  • 2
  • 23
  • 31
kyeeego
  • 187
  • 3
  • 13

5 Answers5

11

try the following :

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

In Typescript

import * as dotenv from 'dotenv'
dotenv.config({path: __dirname + '/.env'})
Abolfazl Roshanzamir
  • 12,730
  • 5
  • 63
  • 79
9

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';
Luke 10X
  • 1,071
  • 2
  • 14
  • 30
Hasan Ahamed
  • 186
  • 3
  • 6
2

try this:

 const path = require('path')
 require('dotenv').config({ path: path.resolve(__dirname, '../.env') })
Abolfazl Roshanzamir
  • 12,730
  • 5
  • 63
  • 79
  • 2
    While this code snippet may solve the question, [including an explanation](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – Clijsters Jan 12 '21 at 08:57
0

try the following

require('dotenv').config()

Abolfazl Roshanzamir
  • 12,730
  • 5
  • 63
  • 79
Mhd Wael Jazmati
  • 636
  • 9
  • 18
0

Change

const { dotenv } = require('dotenv')

to

const dotenv = require('dotenv')
Tamás Sengel
  • 55,884
  • 29
  • 169
  • 223