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!
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.