KellysOnTop23 KellysOnTop23 - 9 days ago 6
Node.js Question

where to store api keys in express node for Heroku

I am finishing up a node express App where I have an API key for Sendgrid and Stripe but I am not sure how to store these in my app that will be deployed on Heroku (also a few other variable I would like to store similarly like db password and what not). I saw online many people were using

process.env
so after some looking I tried using
dotenv
npm and even with some problems with the structure of the app after trying to use the
dotenv
for my sendgrid key I got an error every time.

My question is can somebody supply some detailed instructions or a way to securely store API keys in my node express app that I will be deploying to Heroku?

P.S. I followed a tutorial to implement
Passport.js
for Oauth2 through facebook, google and linkedIn so users can easily log in to the application. The app secrets, id and callbacks are retrieved from a json file in a folder call config in my application. Is this information secure at least in its placement and retrieval in the application? Should I do something similar for my sendgrip and stripe api keys? (picture below)

enter image description here

Answer

You can set up your folder directory like this:

config

config.js

var config = {};
//development
var env = process.env.NODE_ENV || 'development';
if(env === 'development'){
  config = require('./env/development');
}else if (env === 'test'){
    config = require('./env/test');
} else if(env === 'production'){
    config = require('./env/production');
}

module.exports = config;

development.js

var envFile = __dirname + '/env.json';
var jsonfile = require('jsonfile');

var envVars = jsonfile.readFileSync(envFile);

module.exports = {
    value: envVars["VALUE"] 
};

production.js

module.exports = {
    value: process.env.VALUE 
};

test.js

module.exports = {
    value: 'Some value' 
};

The basic idea here is that each developer can configure their own keys in their own env.json file. For production, you can store these in a secure file somewhere and load them into the environment however you want prior to running your application. Using heroku, it makes it easy to configure these environment variables and stores them for you. Check it out here

You can also ommit any details you may not need like development or test stuff.

Comments