Search code examples
node.jsexpressdotenv

Dotenv not loading env variables with correct path


I'm using the dotenv library, but my env variables returns undefined

Here is app.ts:

require('dotenv').config({path: '/.env'});
console.log(process.env.MAIN_DB_PATH) // returns undefined

Here is my .env file:

MAIN_DB_PATH=./data/database.db
UPLOAD_MULTER_DIR=./module/car/uploads

My folder structure is

enter image description here

So it should works fine :(


Solution

  • To load the .env file in a different directory, you need to provide the absolute path to that file.

    • __dirname : the absolute path to the directory of the file where you need to load .env file (app.ts in this case)
    • .. : go 1 level up

    Then path.resolve will give you the absolute path to .env file

    const path = require('path');
    require("dotenv").config({ path: path.resolve(__dirname, '..', '.env') });
    console.log(process.env.MAIN_DB_PATH);