Search code examples
node.jsdotenv

Setting dotenv path outside of root directory is not working


I want to set the path of dotenv config and it does not work. My directory is

myproject/script/.env

myproject/web/src/config.js,

so I set dotenv path in config.js as following, which does not work.

import dotenv from 'dotenv'

dotenv.config({ path: '../../scripts/.env'})

Is it not possible to set path outside of web directory? Because it worked when I put the .env file in web directory. The thing is I want to use another .env file which is in script directory and I can't do it.


Solution

  • A relative path like that is relative to the current working directory (try logging that with console.log(process.cwd())), not relative to the location of the file you're in.

    To make that path relative to your config.js you can do this instead:

    dotenv.config({ path: `${__dirname}/../../scripts/.env` })