using interpolation in .env files

Viewed 3337

I'm trying to use a .env file in a node app and dotenv NPM module to read it, but use some variables and interpolation. what works in a standard bash file doesn't seem to run within a .env config file though. e.g., given:

APP_NAME=tixy
MONGODB_URI="mongodb://127.0.0.1:27017/${APP_NAME}"

will come out directly in code

const mongoUri = process.env.MONGODB_URI

as "mongodb://127.0.0.1:27017/${APP_NAME}"

is there a way to get a .env config to run? perhaps I could 'source' it as the app starts up and use export for all the vars, but that seems kludgey...

1 Answers

dotenv won't expand environment variables, but you could use dotenv-expand in addition to dotenv to get this behavior:

var dotenv = require('dotenv')
var dotenvExpand = require('dotenv-expand')

var myEnv = dotenv.config()
dotenvExpand(myEnv)

// Should be OK now.
const mongoUri = process.env.MONGODB_URI
Related