Twitter Login Using Node and MySQL

Twitter Login using node is one of the tedious task that developer’s are facing now, due to the update of Express and Middle-ware depreciation, old code which is now at first page of Google either does not work, or gives a pain to your ass to make it run.

Live Demo Download Code
In this tutorial i am going to cover complete steps from scratch to develop Twitter Login app using Node with Oauth protocol. Listed down are Steps that we are going to follow, you may skip some if you did or know already.

Steps to follow :

  1. Creating Twitter app and getting App ID and App secret ( same as consumer ID and consumer secret).
  2. Creating package.json and installing dependencies.
  3. Configuring the database to store User information.
  4. Configuring the app information.
  5. Coding the Server file.
  6. Running the app.


Step 1: Creating Twitter App.

Go to the Twitter apps site and sign-in with your twitter account. Create new app with proper name, put call back URL as  if you are also testing it on your local machine.

Twitter not do not allow ‘localhost’, so i use this numeric presentation. Doesn’t make any difference by the way.

For you reference here is the screen shot of the app i am going to use for this tutorial.

Screenshot from 2014-09-05 11:58:35

Once the app is created, you can go to API Keys tab and copy API KEY and API secret which we will need to authenticate user from our app.

Step 2: Package.json and Dependencies :

Due to Express update, we are going to use following middle ware externally.

  • body-parser
  • cookie-parser
  • express-session

For Oauth authentication we are using Passport module which is awesome piece of code i have ever encountered. It is super easy and modular to code.

"name": "passport-twitter-examples-signin",
"version": "0.0.1",
"body-parser": "1.7.0",
"cookie-parser": "1.3.2",
"ejs": "1.0.0",
"express": "4.8.7",
"express-session": "1.7.6",
"mysql": "2.4.3",
"passport": "0.2.1",
"passport-twitter": "1.0.2"

You can install all of these dependencies by typing

npm install

You may require ‘sudo‘ access in Linux or Mac System.

Step 3: Configuring Database (Optional).

For those who want to store the information of user after successful authentication can use this step. Twitter returns the ID of user which is unique and could be stored in database for the further operations.

Open up your phpmyadmin  and create database of proper name. Execute following query to create a User information table.

CREATE TABLE user_info
user_id INT(100) NOT NULL,
user_name VARCHAR(100) NOT NULL,
PRIMARY KEY(user_id)

By using config.js variable you can specify whether you want to use database or not. For just a testing, you can put it as ‘false‘.

Step 4: Configuring the App information.

For your convenience, i have created one configuration file which stores information about :

  • Twitter app
  • You want to use Database or not
  • Database information

If you don’t want to use database for this app, you can put ‘true‘ or ‘false‘ accordingly. This may be useful if you don’t have MySQL database or you have but do not want to use. Here is a configuration file.

* This file contains the configurations information of Twitter login app.
* It consists of Twitter app information, database information.

"twitter-api-key" : "PUT YOUR API KEY",
"twitter-api-secret" : "PUT YOUR API SECRET",
"callback-url" : "PUT CALL BACK URL, USE LOCALHOST",
"use-database" : "TRUE OR FALSE",

Use callback URL as localhost followed by rest. Don’t use here.

Step 5: Coding the Server and Passport.

Passport is node module for Oauth authentication, and we will be using the same for our purpose. We also need Session, cookie-parser, body-parser in order to run our app.

var express = require('express')
, passport = require('passport')
, util = require('util')
, TwitterStrategy = require('passport-twitter').Strategy
, session = require('express-session')
, cookieParser = require('cookie-parser')
, bodyParser = require('body-parser')
, config = require('./configuration/config')
, mysql = require('mysql')
, app = express();

//Define MySQL parameter in Config.js file.
var connection = mysql.createConnection({
host :,
user : config.username,
password : config.password,
database : config.database

//Connect to Database only if Config.js parameter is set.


// Passport session setup.
passport.serializeUser(function(user, done) {
done(null, user);

passport.deserializeUser(function(obj, done) {
done(null, obj);

// Use the TwitterStrategy within Passport.

passport.use(new TwitterStrategy({
consumerKey: config.twitter_api_key,
consumerSecret:config.twitter_api_secret ,
callbackURL: config.callback_url
function(token, tokenSecret, profile, done) {
process.nextTick(function () {
//Check whether the User exists or not using
//Perform MySQL operations.
return done(null, profile);

app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(session({ secret: 'keyboard cat', key: 'sid'}));
app.use(express.static(__dirname + '/public'));

app.get('/', function(req, res){
res.render('index', { user: req.user });

app.get('/account', ensureAuthenticated, function(req, res){
res.render('account', { user: req.user });

app.get('/auth/twitter', passport.authenticate('twitter'));

passport.authenticate('twitter', { successRedirect : '/', failureRedirect: '/login' }),
function(req, res) {

app.get('/logout', function(req, res){

function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) { return next(); }


We have to define Passport Strategy in which we provide App ID, App Secret, callback variable. In the tick function we define further operations to be taken care of after successful authentication to user.

Once the user is authenticated, we check the database for the user ID entry, if exists we won’t add new row else we will.

Running the app.


node app.js

to run the application. You can visit http://localhost:3000 to view the app. After successful Twitter Login, you will be redirected to home page with welcome message.

16 thoughts on “Twitter Login Using Node and MySQL”

  1. What’s up, after reading this awesome article i am too happy to share my familiarity here with mates.

  2. Genesis leichhardt

    Good day I am so happy I found your weblog, I really found you by mistake, while I was looking on Bing for something else, Anyways I am here now and would just like to say thanks for a remarkable post and a all round thrilling blog (I also love the theme/design), I don’t have time to go through it all at the minute but I have book-marked it and also added your RSS feeds, so when I have time I will be back to read a great deal more, Please do keep up the awesome job.

  3. You ought to take part in a contest for one of the best sites online. I will recommend this blog!

  4. Hi,
    i want to sign in to twitter using angularjs. i have consumer key and consumer secret, but i don’t understand how to integrate twitter with angularjs.please help me

  5. Thanks for the good writeup. It in fact was once a entertainment account it. Look advanced to far added agreeable from you! By the way, how could we be in contact?

  6. Hi,
    Thank you so much for this superb code I am able to login into both facebook and twitter, can we have any module so that if we want to access one or more social medias it is easy to import that module and call the required functions ?

  7. can i use this for building a chrome SPA ? I want to make an SPA that will make this button and return their timeline. Will this work with chrome since chrome dev doesn’t allow server side code?

    1. Shahid (UnixRoot) Shaikh


      I am not sure that it will work, for that, I believe you need to write native JS code which runs on browser only to access the twitter API.

  8. What is the MySQL query I should run?

    I want to check if user exists when he tries to login.

Comments are closed.