Twitter Streaming API with Node.js, Socket.io and ReactJS

I have been working in a prototype using the Twitter Streaming API with Socket.io and ReactJS for the frontend, Node.js in the backend, cool stuff!

I used several articles as a reference, the one using the streaming API using socket.io(but AngularJS and ntwitter npm package), real-time django using node.js and socket.io or a modern python stack for a real time web application.

In the end as I said I used nodejs, the twit package and socket.io in the backend. With all these tools was incredibly easy to have something running fast.

This is an example of what could it be.

ReactJS + Node + Twitter Streaming API + Socket.io example from Javier Aguirre on Vimeo.

And these are the different parts composing the example, the installation of the different tools is beyond the scope of this article just because I want to focus more in functionality and I don't want the article to be very long.

Anyway if you have a question/criticism here I am. :-)

You will need to register a Twitter application to access Twitter Streaming API.

Backend, in your app.js:


var http = require('http');
var express = require('express');
var app = express();
//...
var Twit = require('twit');
var T = new Twit({
  consumer_key: config.twitter.consumerKey,
  consumer_secret: config.twitter.consumerSecret,
  access_token: config.twitter.accessToken,
  access_token_secret: config.twitter.accessTokenSecret
});

var server = http.createServer(app).listen(
  app.get('port'), function() {
    console.log('Express server listening on port ' + 
    app.get('port'));
});

var io = require('socket.io').listen(server);
var stream = T.stream('statuses/sample')

io.sockets.on('connection', function (socket) {
  stream.on('tweet', function(tweet) {
    socket.emit('info', { tweet: tweet});
  });
});

The jade view, simple stuff:


extends layout

block content
  script(type='text/javascript', src="/socket.io/socket.io.js")
  script(type='text/jsx', src="javascripts/component.js")
  h1 Authenticated
  div#content

In the id content we will add our ReactJS content (component.js).


/** @jsx React.DOM */
var Tweet = React.createClass({
    render: function() {
        return (
            <li>{this.props.text}</li>
        )
    }
});

var TweetList = React.createClass({
    render: function() {
        var tweets = this.props.data.map(function(tweet) {
            return ;
        });
        return (
            <div>
                <ul>
                    {tweets}
                </ul>
            </div>
        )
    }
});

var TweetBox = React.createClass({
    addTweet: function(tweet) {
        var tweets = this.state.data;
        var newTweets = tweets.concat([tweet]);

        if(newTweets.length > 15) {
            newTweets.splice(0, 1);
        }
        this.setState({data: newTweets});
    },
    getInitialState: function() {
        return {data: []};
    },
    componentWillMount: function() {
        var socket = io.connect();
        var self = this;

        socket.on('info', function (data) {
            self.addTweet(data.tweet);
        });
    },
    render: function() {
        return (
            <div>
                <h1>Hello</h1>
                <TweetList data={this.state.data} />
            </div>
        )
    }
});

React.renderComponent(
  <TweetBox />,
  document.getElementById('content')
);

In componentWillMount we will connect with the socket and create the event listener for the tweets coming from the server.

That's it! With this core features you will be able to have the Twitter Streaming API running in your view.

A bit more advanced version of this example is available at Github.

Javier Aguirre

Read more posts by this author.

comments powered by Disqus