17

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.

4 Answers 4

21

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 
Sign up to request clarification or add additional context in comments.

1 Comment

It was changed to: var dotenv = require('dotenv') var dotenvExpand = require('dotenv-expand') var myEnv = dotenv.config() dotenvExpand.expand(myEnv)
8

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

Comments

3

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/", .... } 

Comments

-1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.