Home > Articles > Open Source > Ajax & JavaScript

  • Print
  • + Share This
This chapter is from the book

Using Twitter’s API with Node.js

Once you create your application within the Twitter Developers website and request an OAuth access token, you are ready to start using the Twitter API. An excellent Node.js module is available for interacting with the Twitter API called ntwitter. This module was initially developed by technoweenie (Rick Olson), then jdub (Jeff Waugh), and is now maintained AvianFlu (Charlie McConnell). All the authors have done an amazing job of abstracting the complexity of interacting with Twitter’s API to make it trivial to get data and do things with it. You continue to use Express in this hour, so the package.json file for the application will include the Express and ntwitter modules.


The ntwitter module uses OAuth to authenticate you, so you must provide four pieces of information:

  • Consumer key
  • Consumer secret
  • Access token key
  • Access token secret

If you requested these when you were setting up the application in the Twitter Developers website, these will be available on the Details page for your application. If you did not request them when you set up the application, you need to do so now under the Details tab. Once you have the keys and secrets, you can create a small Express server to connect to Twitter’s streaming API:

var app = require('express').createServer(),
    twitter = require('ntwitter');


var twit = new twitter({
  consumer_key: 'YOUR_CONSUMER_KEY',
  consumer_secret: 'YOUR_CONSUMER_SECRET',
  access_token_key: 'YOUR_ACCESS_TOKEN_KEY',
  access_token_secret: 'YOUR_ACCESS_TOKEN_KEY'

Of course, you need to remember to replace the values in the example with your actual values. This is all you need to start interacting with Twitter’s API! In this example, you answer the question, “Is there more love or hate in the world?” by using real-time data from Twitter. You request tweets from Twitter’s streaming API that mention the words “love” or “hate” and perform a small amount of analysis on the data to answer the question. The ntwitter module makes it easy to request this data:

twit.stream('statuses/filter', { track: ['love', 'hate'] }, function(stream) {

  stream.on('data', function (data) {

This requests data from the 'statuses/filter' endpoint that allows developers to track tweets by keyword, location, or specific users. In this case, we are interested in the keywords 'love' and 'hate'. The Express server opens a connection to the API server and listens for new data being received. Whenever a new data item is received, it writes the data to the console. In other words, you can see the stream live for the keywords “love” and “hate” in the terminal.

  • + Share This
  • 🔖 Save To Your Account