Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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);

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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);

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading