Facebook Login is widely used as an authentication module on websites. Instead of asking user manual details such as email and password and then verify them, it’s better to use already verified user details.

In this article, we are going to learn and implement a Facebook Login System using Nodejs and ExpressJS. You can download the code by clicking the button below.

If you are new to Node and Express then you won’t regret taking our Node course. It’s FREE!

Creating Facebook App:

Very first thing you going to need is AppID and AppSecret from Facebook App. Please go to Facebook Developers and create your app.

Choose Website as platform when it ask. Give the proper name and you can leave the namespace field blank.

It will ask for Captcha, enter it carefully and once done it will redirect you to the app page. By authenticating your facebook account again you can view the App secret. Now go to Setting and add the Web as a platform.

If you want to test the app in localhost environment then add localhost:3000 as an site address.

The app is set. Let’s go ahead and create our App using Node.

Configuring our Node App:

In the source directory go to the configuration/config.js and update the Facebook AppID and AppSecret. If you want to use Database to store and validate user information you can put the configuration field as true or false. To know the database design for the app please visit twitter login using node article.

configuration/config.js

module. exports = {

"facebook_api_key" : "FB APP ID" ,

"facebook_api_secret" : "FB API SECRET" ,

"callback_url" : "http://localhost:3000/auth/facebook/callback" ,

"use_database" : false ,

"host" : "localhost" ,

"username" : "root" ,

"password" : "" ,

"database" : "Database Name"

}

Update the code with Facebook App information.

Route of Our App:

Routes Action /auth/facebook Authenticate User with Facebook /auth/facebook/callback Get the user information from if login successfully /logout Logging out from App.

Configuring Passport:

I am using Passport node package for the OAuth authentication. It requires configuration of some parameters. Here is our Passport configuration code.

app.js

/*config is our configuration variable.*/

passport. use ( new FacebookStrategy ( {

clientID : config. facebook_api_key ,

clientSecret : config. facebook_api_secret ,

callbackURL : config. callback_url

} ,

function ( accessToken , refreshToken , profile , done ) {

process. nextTick ( function ( ) {

//Check whether the User exists or not using profile.id

if ( config. use_database ) {

//Further code of Database.

}

return done ( null , profile ) ;

} ) ;

}

) ) ;

Complete Server Code:

Here is our app.js with complete routing and Passport code.

app.js

const express = require ( 'express' )

, passport = require ( 'passport' )

, FacebookStrategy = require ( 'passport-facebook' ) . 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.

const pool = mysql. createPool ( {

host : config. host ,

user : config. username ,

password : config. password ,

database : config. database

} ) ;



// Passport session setup.

passport. serializeUser ( function ( user , done ) {

done ( null , user ) ;

} ) ;



passport. deserializeUser ( function ( obj , done ) {

done ( null , obj ) ;

} ) ;





// Use the FacebookStrategy within Passport.



passport. use ( new FacebookStrategy ( {

clientID : config. facebook_api_key ,

clientSecret : config. facebook_api_secret ,

callbackURL : config. callback_url

} ,

function ( accessToken , refreshToken , profile , done ) {

process. nextTick ( function ( ) {

//Check whether the User exists or not using profile.id

if ( config. use_database ) {

// if sets to true

pool. query ( "SELECT * from user_info where user_id=" + profile. id , ( err , rows ) => {

if ( err ) throw err ;

if ( rows && rows. length === 0 ) {

console. log ( "There is no such user, adding now" ) ;

pool. query ( "INSERT into user_info(user_id,user_name) VALUES('" + profile. id + "','" + profile. username + "')" ) ;

} else {

console. log ( "User already exists in database" ) ;

}

} ) ;

}

return done ( null , profile ) ;

} ) ;

}

) ) ;





app. set ( 'views' , __dirname + '/views' ) ;

app. set ( 'view engine' , 'ejs' ) ;

app. use ( cookieParser ( ) ) ;

app. use ( bodyParser. urlencoded ( { extended : false } ) ) ;

app. use ( session ( { secret : 'keyboard cat' , key : 'sid' } ) ) ;

app. use ( passport. initialize ( ) ) ;

app. use ( passport. session ( ) ) ;

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/facebook' , passport. authenticate ( 'facebook' , { scope : 'email' } ) ) ;





app. get ( '/auth/facebook/callback' ,

passport. authenticate ( 'facebook' , { successRedirect : '/' , failureRedirect : '/login' } ) ,

function ( req , res ) {

res. redirect ( '/' ) ;

} ) ;



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

req. logout ( ) ;

res. redirect ( '/' ) ;

} ) ;





function ensureAuthenticated ( req , res , next ) {

if ( req. isAuthenticated ( ) ) { return next ( ) ; }

res. redirect ( '/login' )

}



app. listen ( 3000 ) ;

Designing our View:

index.ejs

<% if ( !user ) { %>

div style = "width:500px;height:180px;" >

h2 style = "font-size:40px;" > / h2 >

a href = "/auth/facebook" >< src = "fb-login.jpg" width = "151" height = "24" >< / a > >< img >

/ div >

<% } else { %>

h2 > <% = user.displayName %> . / h2 >

<% } %> Welcome! Please log in.Hello,

Once user login we just have to show the values return from Facebook. Here it is.

p > ID : <% = user. id %>< / p >

< p > Name :<% = user.displayName %>< / p > :

Running our App:

Download the code and update the config.js with the Facebook app information. Then run

npm install

to install dependencies and then run app using

node app.js

Visit localhost:3000 to view the app.

Login using your Facebook account and allow the app permission. After successful authentication, you will be redirected to your specified callback URL.

Conclusion

We learned how to use and implement Facebook login system using Passport module. We used to express to develop the web server and MySQL to store user information.

Further Study

Learn more!

Twitter Login Using Node and MySQL

Facebook Status Box using Node.js and MySQL

HTML5 Push Notification System Using Nodejs MySQL Socket.io

How to Replace All Occurrences of a String in JavaScript