4

I have a simple app I'm working on that uses the Google Maps API, and Darksky API; I've installed dotenv to handle hiding the keys for both. After following the Docs I was able to make this work but only in the file where dotenv in being required (app.js). I need access to the ENV variables in my footer.ejs file, and a weather.js file but process.env is not defined in them. Do I have to export dotenv? How do this? Thanks, in advance.

app.js

var express = require('express'),
Dotenv = require('dotenv').config(),
app = express(),
bodyParser = require('body-parser'),
mongoose = require('mongoose');

mongoose.connect(process.env.DB_URL);
app.use(bodyParser.urlencoded({extended: true}));
app.set('view engine', 'ejs');
app.use(express.static(__dirname + '/assets'));

// HomePage
app.get('/',function(req, res){
  res.render('home');
});

app.listen(process.env.PORT || process.env.LOC_PORT,function(err){
  if (err) return console.log(err);
  console.log('Server Running: '+ process.env.LOC_PORT);
});

1 Answer 1

1

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

3 Comments

Thanks, for the help. I'm getting an, 'Unexpected token import' error from weather.js, and a 'require is not defined' error from env.js.
@halfacreyum Sorry, this is ES6 syntax, you can just use require as well and replace consts in my answer with vars.
Sorry, I did switch const's to var's I should of mentioned that. I'm still getting the error from the env.js file ('require is not defined'), I'm loading the script for that file in the footer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.