Twitter Firestarter

For Twitter and Firebase it might as well be Valentines Day everyday, these two are made for each other.

Here is a finished working example of what we are going to build together, and the corresponding Github Repo if you just want to clone and play.

Thats right, by the end of this post we are going to have built a simple full stack app that streams all the tweets containing the phrase ‘NFL’ and puts them on a page deployed to the world.

I am going to assume that you have basic knowledge of JavaScript (if not, there are a ton of great resources out there) plus the latest versions of both Node and NPM installed. I am also going to assume you are on a Mac. I am using Atom as a text editor, but this should work just fine with Sublime as well.

Ready? Set. Let’s Go!

Open up your terminal (or iTerm etc.) and type without the ‘$’:

$ mkdir twitter-firestarter

We just made our fancy directory! Make sure you put this somewhere it is easy to find for you. Ie. on your desktop or in a ‘projects’ folder.

$ cd twitter-firestarter

Change into the spanking new directory we just made

$ touch index.html app.js twitter.js

Using ‘touch’ on the command line is the same thing as telling your computer that you want to ‘create’ these files. Here we are creating our front end (index.html + app.js) and our backend (twitter.js)

$ npm init 

When you are prompted for info here, just hit enter a bunch of times. These bits are irrelevant for what we are building today.

NPM stands for Node Package Manager. NPM gives you access to 100s of thousands of packages that other developers have open sourced that you can utilize in your own applications. In this case we are going to use packages for accessing the Twitter API and Firebase.

$ atom . 

This opens the current folder(in our case ‘twitter-firestarter’) with our text editor Atom. You can try ‘sublime .’ if you are are using sublime or just open your editor and navigate to wherever you put ‘twitter-firestarter’ and open it manually.

Glad we got that out of the way! Now time for a little pro tip…

We are going to use a little code editor magic! In the preferences for your editor (which you can find by clicking ‘Atom’ at the top of your screen with your editor open), click on ‘install’ and search for and install a package called ‘emmet’. (Here is a video incase you get stuck: How to install an Atom package)

Packages are a great way to improve the productivity of text editor. There are a ton of great packages out there. Here are a few posts on good ones to install for Atom.

With Emmet installed, open index.html in Atom and type:

 !

then hit tab directly after the ‘!’, thats it. Are you sufficiently wowed by the resulting magic?

<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8">
<title>Document</title>
</head>
<body>
</body>
</html>

With two quick keystrokes we have the makings of our wonderful html page. While we are here, lets include jQuery via CDN (we want the min version), add a div where we will eventually put our tweets and properly title our page.

Index.html should now look like this with the changes highlighted:

<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8">
<title>Twitter Firestarter</title>
<script src=”https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.min.js"></script>
</head>
<body>
<div class='tweets'></div>
</body>
</html>

Great! Now lets head over to the twitter.js file we created and start building our backend with Node. We are going to need to utilize a Twitter NPM package to make our lives a lot easier. The same way Atom packages can improve your productivity NPM packages can hugely boost your productivity in development.

So at the top of twitter.js type:

‘use strict’;
var Twitter = require(‘twitter’);

Here we are assigning the variable ‘Twitter’ to a required NPM package that someone else has written called ‘twitter’. Thats it! Just that one simple line allows us to utilize a NPM library that makes interacting with the Twitter API very straightforward.

<insert mind blown graphic />

Now lets open up a terminal and see where we are at by entering:

$ node twitter.js

What?!? Crazy error message. But the important line is:

Error: Cannot find module ‘twitter’

We have ‘required’ the twitter module in our file but haven’t installed the module via npm. Its like we have told the computer that we are using a file without telling the computer where that file is actually located. So lets head back to terminal and fix that by typing the following and hitting enter to install the npm package in our program:

$ npm install --save twitter

Small side note, its important that you install the module in the right directory. So make sure you are in the ‘twitter-firestarter’ directory when you run the command above.

Computers are actually really dumb. You need to tell them explicitly where to look for things otherwise it wont’t be able to find them. Incorrectly referencing the location (or path) to a file or resources is probably the #1 mistake I made while learning to become a developer. If you are having errors in your programs, a good place to start looking is making sure that everything is pointing at the right path.

Alright, lets try to run our program again from the terminal to make sure the package installed correctly by trying the following command again :

$ node twitter.js

If absolutely nothing happened we are on the right track! If there are errors, head further up the page and check if you mistyped something. Or tweet at me and I will give you a hand.

Alright, lets head over to the Twitter NPM package’s site and grab a couple snippets of code we are going to need.

If you take a minute or two to look over Twitter package page, it will show you many things that you can do with the Twitter api. For our purposes, we are only interested in connecting to the Twitter API and accessing the streaming data. But there is a whole world of opportunity on this page.

Any action you can perform on Twitter.com there is a corresponding API call in this package. Its pretty neat stuff :)

Ok, lets open twitter.js again in our editor and type in the following:

‘use strict’;
var Twitter = require(‘twitter’);
var client = new Twitter({
consumer_key: ‘’,
consumer_secret: ‘’,
access_token_key: ‘’,
access_token_secret: ‘’
});
client.stream(‘statuses/filter’, {track: ‘nfl’}, function(stream) {
stream.on(‘data’, function(tweet) {
console.log(tweet.text);
});

stream.on(‘error’, function(error) {
throw error;
});
});

This is really the core of our program. We are going to connect to Twitter’s api and then track a stream on the ‘nfl’.

Take a moment to read this line by line to ensure you at least some what of an idea of what is going on. It is pretty readable from a human perspective.

Lets try to run our program again:

$ node twitter.js

What? Nothing happens. Two extra bonus points if you can guess why!!

Alright, I will help you out :) If you look at the code above you will see that we are missing our keys to access the Twitter API. All four of the key slots are just sitting on blanks. Lets fix that by going to get ourselves some API keys for Twitter!

Signing up for Twitter API

I am going to assume that you already have a Twitter account. If not, go and grab one. Then:

  1. Head to apps.twitter.com
  2. Click ‘create new app’
  3. Fill in the ‘name’, ‘description’ and ‘website’ fields and click ok to the terms. It shouldn’t matter what your website is, so long as it is a valid url
  4. On the next screen, click on the ‘Keys and Access Tokens’ tab.
  5. At the top under ‘Application Settings’ copy the ‘Consumer Key’ (something like ix78CQpA0LNRTAFapOj3xxxxx) and the Consumer Secret (something like yynBZnrQHzeOhyIvjjg3Iij3WGWbdBnY7w90fMVd73Hwg5xxxx) into the appropriate slots in twitter.js.
  6. Next scroll down the page a bit and click the ‘create my access token’ button. And copy and paste similar to above into the appropriate sections in twitter.js

Your twitter.js file should look something like this:

var client = new Twitter({
consumer_key: ‘ix78CQpA0LNRTAFapOj3xxxxx’,
consumer_secret: ‘yrQHzeOhyIvjjg3Iij3WGWbdBnY7w90fMVd73Hwg5xxxx’,
access_token_key: ‘22101689-k5apKndocYohPtQ6W3oFEqQKg6h3RvTOCxxxx’,
access_token_secret: ‘JEUOdXwNCfH8HtcVa9QDy4OP82mGhOaStazQ6tPxxxx’
});

Lets try running our program again in the terminal:

$ node twitter.js

Boom! Our console has come alive with a stream of NFL related tweets. How neat is that? And with only a few lines of JavaScript. Lets shut the stream down for the moment by hitting ‘Control’ and ‘c’ at the same time on our keyboard.

Now that we have figured out a way to have the tweets coming into our console we need to get them onto a screen for the whole world to see! This is where Firebase comes in to allow us to relay between the back end and front end of our application.

Signing up for Firebase

  1. Head over to Firebase.com
  2. Click the ‘Sign-Up with Google’ Button
  3. When you get to the Welcome screen, click in the top left hand (sort of greyed-out) box, pick a name for your app and click create
  4. click on ‘Manage app’ for you newly created app
  5. copy the url in the address bar in your browser. It should look something like: ‘https://your-neat-name.firebaseio.com/’

Super! We are nearly there, lets head back to twitter.js and add the Firebase npm package to get things going. Right at the top of the document (before our client keys for Twitter) add the following:

‘use strict’;
var Twitter = require(‘twitter’);
var Firebase = require(‘firebase’);
var ref = new Firebase(“https://your-neat-name.firebaseio.com/");

Where of course your url is the one that you copied from firebase in step 5 above. What is going on here is that we are creating a connection between our twitter.js program and our firebase datastore. Now whenever we reference the variable ‘ref’ we will be talking directly to data stored at that location on our very own Firebase.

Let’s fire up our program once again and see where things are at:

$ node twitter.js

What!?! Bet you recognize this error already. One bonus point if you already know how to fix it. Got it?

If you guessed that we have to add a firebase package via npm, you are correct! In the terminal, enter:

npm install --save firebase

Alright, lets send some data to Firebase! To do this we simply replace the console.log with a firebase reference. So inside of twitter.js change:

stream.on(‘data’, function(tweet) {
console.log(tweet.text);
});

To this:

stream.on(‘data’, function(tweet) {
ref.push(tweet.text);
});

Simple as that, instead of logging the data to the console. We are pushing it up to firebase! There is a bunch of ways you can push data to firebase, and their docs are incredibly readable. You can perform all basic CRUD operations with Firebase, which is really the core of any web application.

So? We are good to go! Don’t believe me? Open up your terminal and enter:

node twitter.js

Nothing happens in the console ?!?! Remember, we removed the ‘console.log()’ line. So let’s head over to your Firebase that you set up earlier and Boom! Watch a stream of NFL tweets rain down on your screen. Pretty neat, huh?

Getting from Firebase to your screen

Alright, time for the last step! Lets get those tweets from Firebase into our index.html file and out there for the whole world to see :)

As a final reminder, here is what your twitter.js should look like:

‘use strict’;
var Twitter = require(‘twitter’);
var Firebase = require(‘firebase’);
var ref = new Firebase(“https://your-firebase-url.firebaseio.com");
var client = new Twitter({
consumer_key: ‘YOUR KEY HERE’,
consumer_secret: ‘YOUR KEY HERE’,
access_token_key: ‘YOUR KEY HERE’,
access_token_secret: ‘YOUR KEY HERE
});
client.stream(‘statuses/filter’, {track: ‘nfl’}, function(stream) {
stream.on(‘data’, function(tweet) {
ref.push(tweet.text);
});
stream.on(‘error’, function(error) {
throw error;
});
});

Now, lets head back to our index.html. Just like with twitter.js, we need to tell this file where to look for our firebase. Remember, computers are dumb (really!)

First we need to tell our index.html file all about Firebase, the same way we did about jQuery, by including the reference to the correct CDN script.

Then we need to connect our index.html file to our app.js file. Easy as pie:

<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8">
<title>Twitter Firestarter</title>
<script src=”https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.min.js"></script>
<script src="https://cdn.firebase.com/js/client/2.3.1/firebase.js"></script>
<script src=”app.js”></script>

</head>
<body>
<div class=’tweets’></div>
</body>
</html>

Now lets open up our app.js file and wire that up to our firebase to rain down our tweets!

‘use strict’;
var ref = new Firebase(“https://your-firebase.firebaseio.com/");
ref.on(‘child_added’, function(snap) {
$(‘.tweets’).prepend(snap.val())
})

There are a couple of things going on here. First, we are establishing a connection to our firebase just like before so that our front end knows where to look for data. Thats the ‘var ref= new Firebase….’ bit.

Then we are saying that every time a ‘child_added’ event occurs at our ‘ref’ we want Firebase to send us a copy of the data.

Check out the docs on retrieving data via Firebase. There are a number of different event listeners that may suit your needs. Here we use ‘child_added’ which grabs a copy of everything that exists at that point in time and then fires a new event for each new item added. So each time a new tweet is added to our Firebase, a copy is relayed to our front end.

Finally, we are using the smallest amount of jQuery to prepend that new tweet to our ‘tweets’ div.

Now all we need to do is open our index.html file in our browser to see the wonder that is NFL Twitter land! Assuming you use Google Chrome, click file, open-file and navigate to wherever you have saved your index.html file. Your NFL tweets await!!

The Lastest of Last Steps (Promise)

One final thing we need to do, although its cool that we can open this file and look at it on our own computer, wouldn’t it be neat if we could show this to our friends all over the world as well?

We are going to use Firebase’s deployment process to ship this beauty out to the world. Head back to your Firebase and click the ‘hosting’ tab on the left hand side. In your terminal:

$ npm install -g firebase-tools 

or if that doesn’t work use the following and enter your password when prompted

$ sudo npm install -g firebase-tools

Then back in your terminal in our ‘twitter-firestarter’ folder enter:

$ firebase init

In the init process that pops up in your console click on the name of your firebase and then hit enter for the ‘public’ directory. We are going to have to make a small change to our file structure here moving index.html and app.js inside of the newly created ‘public’ folder.

So our file structure should now look something like

-twitter-firestarter
-public
-app.js
-index.html
  -twitter.js

Then we enter in the terminal:

$ firebase deploy

followed by

$ firebase open

Boom! You now have a live link to share with the world with all your beautiful tweets about the ‘nfl’! Here’s my finished example. It’s not pretty, but it works and now you can apply a small amount of Bootstrap or CSS to dress it up for a night on the town!

If you happened to stumble at some point along the way, let me know in the comments, fire me an email at: jesse.heaslip@gmail.com or hit me up on Twitter. Up next I will walk you through using Firebase Authentication.

Have fun Firebasing!

If you found this post useful, please click the little green heart below and share the love! Thanks