Search code examples
node.jses6-modulesdotenv

Using DOTENV correctly


I have a db.js file like so

import "dotenv/config";

const devConfig = `"${process.env.PG_USER}://${process.env.PG_USER}:${process.env.PG_PASSWORD}@${process.env.PG_HOST}:${process.env.PG_PORT}/${process.env.PG_DATABASE}"`;

const prodConfig = process.env.DATABASE_URL;

const dbConnection =
  process.env.NODE_ENV === "production" ? prodConfig : devConfig;

console.log(dbConnection);

export default dbConnection;

The console.log function correctly outputs the string that I need (which is "postgres://postgres:learn@sql@localhost:5432/EPL" in my case)

However, when I am trying to use import the dbConnection variable in another file, all I get is "undefined://undefined:undefined@undefined:undefined/undefined".

The code of the file that I am trying to use the dbConnection variable is like below.

import pgPromise from "pg-promise";
import dbConnection from "../db.js";

const pgp = pgPromise({});
const db = pgp(dbConnection);
console.log(dbConnection);

What am I doing wrong?


Solution

  • By default, dotenv looks for the .env file in the current working directory, ie the directory you are in when running your app...

    Path
    Default: path.resolve(process.cwd(), '.env')

    If you run node query.js, then your CWD is whatever directory query.js lives in and dotenv will look for .env in that directory.

    If you want to force dotenv to look in the same directory as your db.js file, the ES module version looks like this...

    // db.js
    import { dirname, resolve } from "path";
    import { fileURLToPath } from "url";
    import dotenv from "dotenv";
    
    dotenv.config({
      path: resolve(dirname(fileURLToPath(import.meta.url)), ".env"),
    });
    
    // create and export your connection strings...
    

    If you weren't using ES modules, it would look more like this

    const { resolve } = require("path");
    require("dotenv").config({ path: resolve(__dirname, ".env") });