Search code examples
javascriptnode.jsenvironment-variablespg-promisedotenv

DOTENV not reading variables properly


This is my file:

postgresU="myuser"
postgresP="mypass"
postgresH="myhost"
postgresDB="mydb"
postgresC="postgres://${postgresU}:{$postgresP}@{$postgresH}:5432/${postgresDB}"

In my nodejs app,

require('dotenv').config();
var connectionString = process.env.postgresC;
console.log("Connection String:",connectionString);

This prints:

Connection String: "postgres://${postgresU}:${postgresP}@${postgresH}:5432/${postgresDB}"

What am I doing wrong?


Solution

  • You can use a package like dotenv-expand if you want to expand variables in .evn files.

    Once installed (with npm or yarn) you can simply use a .env file with:

    postgresU="myuser"
    postgresP="mypass"
    postgresH="myhost"
    postgresDB="mydb"
    postgresC="postgres://${postgresU}:${postgresP}@${postgresH}:5432/${postgresDB}"
    

    and then process it with:

    const dotenv= require('dotenv')
    const dotenvExpand = require('dotenv-expand')
    let myEnv = dotenv.config()
    dotenvExpand(myEnv)
    
    let connectionString = process.env.postgresC;
    console.log(connectionString)
    

    postgres://myuser:mypass@myhost:5432/mydb