Accessing ENV var in different files in Node.js using dotenv Accessing ENV var in different files in Node.js using dotenv express express

Accessing ENV var in different files in Node.js using dotenv


You can create env.js file, that export you environment variables as follow:

const dotenv = require('dotenv');module.exports = {  getEnvVariables: function () {    const vars = dotenv.load();    const jsonVars = {};    for (const key in vars) jsonVars[key] = JSON.stringify(vars[key]);    return jsonVars;  },};

Then just import {getEnvVariables} from './env'; after that.

In case you're using Webpack, you may add the following plugin to your weback configuration file so you dont't need to put the import line in any file across your app anyomore:

new webpack.DefinePlugin({  'process.env': env.getEnvVariables()}),