Variable assignment withing .env file Variable assignment withing .env file express express

Variable assignment withing .env file


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

Steps :

First Install :

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

Then Change .env file like :

NODE_ENV = localPORT = 4220IP = 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 lineprocess.env.PROFILE_UPLOAD; // to access the .env variable


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.jsconst BASE_URL = `http://${process.env.IP}:${process.env.PORT}/`module.exports = { PROFILE_UPLOAD: BASE_URL+"uploads/profile/", POST_UPLOAD: BASE_URL+"uploads/discussion/", ....}


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