Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using interpolation in .env files

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...

like image 862
dcsan Avatar asked Jun 30 '19 07:06

dcsan


People also ask

Can I use variables in .env file?

The . env file contains the individual user environment variables that override the variables set in the /etc/environment file. You can customize your environment variables as desired by modifying your . env file.

Should you commit your .env file?

env files to version control (carefully) Many software projects require sensitive data which shouldn't be committed to version control. You don't want Bad Guys to read your usernames, passwords, API keys, etc.

What should .env files contain?

env file should be particular to the environment and not checked into version control. This. env. example file documents the application's necessary variables and can be committed to version control.


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
like image 119
Mureinik Avatar answered Oct 21 '22 17:10

Mureinik