I’ve been teaching myself node.js using some tutorials online. I successfully made a Twitter bot and deployed it using Heroku and everything works great.
However, my Twitter API keys are contained in a config.js file that is freely available on the github repository that my Heroku app is linked to. I’ve since removed this sensitive data from github.
I have searched for answers on this and have found a lot of conflicting and confusing solutions and was hoping somebody could direct me to an easy-to-follow solution. If my API keys are not available on the git, where do I store them and how do I instruct my app to retrieve them?
This is the main app.js file, note I’ve combined a couple of different tutorials and so what it does is provide a “Hello World” output on screen and also Tweets “Hello, learning node.js!” on my chosen Twitter account:
const http = require('http');
const port=process.env.PORT || 3000
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/html');
res.end('<h1>Hello World</h1>');
});
server.listen(port,() => {
console.log(`Server running at port `+port);
});
var Twit = require('twit')
var fs = require('fs'),
path = require('path'),
Twit = require('twit'),
config = require(path.join(__dirname, 'config.js'));
var T = new Twit(config);
T.post('statuses/update', { status: 'Hello, learning node.js!' },
function(err, data, response) {
console.log(data)
});
The config.js file referenced above looks like:
var config = {
consumer_key: 'xxx',
consumer_secret: 'xxx',
access_token: 'xxx',
access_token_secret: 'xxx'
}
module.exports = config;
This all works with the correct keys in the config.js file, but obviously this is not ideal security-wise!
I’m a bit of a novice here as you can tell, but keen to learn what the correct approach would be to resolve this. Many Thanks in advance!
3
Answers
Thanks for this. I added the environment variables on Heroku (via desktop, not using CLI), and then changed my config.js file to:
Heroku let you set some environment variables, more details here, and you can get them with
process.env.MY_ENV_VAR
.This is a recommended way for building applications referring to the Twelve-Factor App.
I don’t know a lot about heroku but I guess you can set environment variables.
And to have access to these variable in your dev machine, you can set them in a .env file or directly in your computer environment variable. If you want to use a
.env
file, then I guess you’ll need the npm dotenv module (and obviously add.env
to your.gitignore
).For your exemple you could have the following
.env
file :Then you can use them with
process.env.VAR_NAME
so if you want the consumer key you can doprocess.env.consumer_key
. Usually these variables are named uppercase tho.It’s also commonly used to set a
NODE_ENV
variable which allow you to determine if you are running indevelopment
,production
,test
… mode