In the dotenv documentation, it is shown that the .env file is assumed to be in the current directory.
Path Default: path.resolve(process.cwd(), '.env')
process.cwd()
method returns the current working directory of the Node.js process.
Specify a custom path if your file containing environment variables is
located elsewhere.
require('dotenv').config({ path: '/custom/path/to/.env' })
In your case, because your env file is located in the root directory you should specify a custom path for the .env
file.
For example, my github.env
is placed in the root directory and I use dotenv as following:
require('dotenv').config({path:'github.env'});