Vivek Doshi
Vivek Doshi

Reputation: 58603

Variable assignment withing .env file

I have one .env file , that looks like :

NODE_ENV = local
PORT = 4220
BASE_URL = "http://198.**.**.**:4220/"

PROFILE_UPLOAD = http://198.**.**.**:4220/uploads/profile/
POST_UPLOAD = http://198.**.**.**:4220/uploads/discussion/
COMPANY_UPLOAD = http://198.**.**.**:4220/uploads/company/
ITEM_UPLOAD  = http://198.**.**.**/uploads/item/
GROUP_UPLOAD  = http://198.**.**.**/uploads/group/

I want to do something like this :

NODE_ENV = local
IP = 198.**.**.**
PORT = 5000
BASE_URL = http://$IP:$PORT/

PROFILE_UPLOAD = $BASE_URL/uploads/profile/
POST_UPLOAD = $BASE_URL/uploads/discussion/
COMPANY_UPLOAD = $BASE_URL/uploads/company/
ITEM_UPLOAD  = $BASE_URL/uploads/item/
GROUP_UPLOAD  = $BASE_URL/uploads/group/

Expected result of BASE_URL is http://198.**.**.**:4220/

I have tried many few syntax but not getting computed values

Tried Syntax : "${IP}" , ${IP} , $IP

I have used dotenv package , for accessing env variables.

Upvotes: 17

Views: 17185

Answers (4)

Vivek Doshi
Vivek Doshi

Reputation: 58603

dotenv-expand is the solutions as @maxbeatty answered , Here are the steps to follow

Steps :

First Install :

npm install dotenv --save
npm install dotenv-expand --save

Then Change .env file like :

NODE_ENV = local
PORT = 4220
IP = 192.***.**.**
BASE_URL = http://${IP}:${PORT}/

PROFILE_UPLOAD = ${BASE_URL}/uploads/profile/
POST_UPLOAD = ${BASE_URL}/uploads/discussion/
COMPANY_UPLOAD = ${BASE_URL}/uploads/company/
ITEM_UPLOAD  = ${BASE_URL}/uploads/item/
GROUP_UPLOAD  = ${BASE_URL}/uploads/group/

Last Step :

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

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

process.env.PROFILE_UPLOAD; // to access the .env variable

OR (Shorter way)

require('dotenv-expand')(require('dotenv').config()); // in just single line
process.env.PROFILE_UPLOAD; // to access the .env variable

Upvotes: 21

maxbeatty
maxbeatty

Reputation: 9325

dotenv-expand was built on top of dotenv to solve this specific problem

Upvotes: 8

sharkdawg
sharkdawg

Reputation: 984

As already stated you can't assign variables in .env files. You could move your *_UPLOAD files to a config.js file and check that into .gitignore , then you could do

//config.js

const BASE_URL = `http://${process.env.IP}:${process.env.PORT}/`

module.exports = {
 PROFILE_UPLOAD: BASE_URL+"uploads/profile/",
 POST_UPLOAD: BASE_URL+"uploads/discussion/",
 ....
}

Upvotes: 3

Alex Michailidis
Alex Michailidis

Reputation: 4153

Unfortunately dotenv can't combine variables. Check this issue to see more and find a solution for your project.

Upvotes: -1

Related Questions