node.jsexpress.env

Can't access .env file


I can't access .env file from anywhere other than server.jsserver.js, I tried to access it in db.jsdb.js and config.jsconfig.js

I tried this, it works but any better and easy way of doing it?.

import dotenv from "dotenv";
import { fileURLToPath } from 'url';
import path from "path";

const __filename = fileURLToPath(import.meta.url);

const envPath = path.resolve(path.dirname(__filename), "../../backend/.env");

dotenv.config({ path: envPath });

var password = process.env.password;

console.log(password);

Solution

  • You don't need to setup dotenv in every file. You have to execute dotenv.config() before importing app in server.js. for example:

    This will work:

    const dotenv = require("dotenv");
    // Needs to executed first
    dotenv.config();
    
    // Then import other files
    const { db } = require("./internal/db");
    
    
    
    console.log(db);