facebook login with nodejs and ejs template

facebook login with nodejs and ejs template


In this article, I am going to explain login with facebook in nodejs application. As we have already discussed login with twitter and github.

So let's start proceeding with this by creating app id and app secret.

Create App Id and App Secret on facebook

As I told earlier, at first we need App ID and AppSecret from Facebook. For creating your app id and app secret go to Facebook Developers. Enter desired name of app and fill mendatory fields.

facebook login image


After filling the above fields, Add the Web as a platform. Now we are done with Facebook app creation task.


Now lets configure the task at nodejs end, So lets see our server.js file, which is having all the major task at nodejs end.


var express = require('express'), 
    passport  = require('passport'),
    util  = require('util')
    FacebookStrategy  = require('passport-facebook').Strategy,
    session = require('express-session'),
    cookieParser  = require('cookie-parser'),
    bodyParser  = require('body-parser'),
    mysql =require('mysql'),
    app =  express();
//Connection setup with mysql...
var connection = mysql.createConnection({
    host     :  "localhost",
    user     :  "root",
    password :  "Techugo@123",
    database :  "taggnet"
app.use(bodyParser.urlencoded({ extended: false }));
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.static(__dirname + '/public'));
// session related task & passport intiallization...
app.use(session({ secret: 'jsonworldplaceforjsdemos'}));
// Passport session setup.
passport.serializeUser(function(user, done) {
    done(null, user);
passport.deserializeUser(function(obj, done) {
    done(null, obj);
// Using FacebookStrategy within Passport here to perform the actual task...
passport.use(new FacebookStrategy({
    clientID: "*********",
    clientSecret: "*****************************",
    callbackURL: "http://localhost:3000/auth/facebook/callback",
function(accessToken, refreshToken, profile, done) {
    process.nextTick(function () {
      //Check whether the User is already registered or a new user...
      connection.query("SELECT * from user_master where user_id="+profile.id,function(err,rows,fields){
        if(err) throw err;
            console.log("There is a new user, registering here");
            connection.query("INSERT into user_master(user_id,user_name,full_name) VALUES('"+profile.id+"','"+profile.username+"','"+profile.displayName+"')");
            return done(null, profile);
              console.log("User already registered in database...");
              return done(null, profile);
app.get('/', function(req, res){
  res.render('index', { user: req.user }); 
app.get('/auth/facebook', passport.authenticate('facebook',{scope:'email'}));
  passport.authenticate('facebook', { successRedirect : '/', failureRedirect: '/login' }),
  function(req, res) {
app.get('/logout', function(req, res){
function ensureAuthenticated(req, res, next) {
  if (req.isAuthenticated()) { return next(); }
  console.log('server running on port:3000')


In the above file, At top we have included the needed nodejs package with passport related packages. Below that we have created connection with mysql. And below that we have configured passport. And at bottom we have defined the routing in our app.


Now lets come to the view part, have a look our ejs file. Let's have a look on index.ejs file.


<title>Facebook Login using Node and Express</title>
<% if (!user) { %>
<div style="width:500px;height:180px;background-color:#ececec;padding:80px;margin-left:22%;margin-top:9%;">
    <h2 style="font-size:40px;">Welcome! Please log in.</h2>
    <a href="/auth/facebook"><img src="fb-login.jpg" width="171" height="34"></a>
<% } else { %>
    <div style="width:500px;height:180px;background-color:#ececec;padding:80px;margin-left:22%;margin-top:9%;">
          <h2>Hello, <%= user.displayName %>.</h2>
         <a style="padding-right:10px;" href="/">Home</a> |
            <a style="padding-right:10px;" href="/logout">Log Out</a>
        <h3>My Profile</h3>
       <p>ID: <%= user.id %></p>
       <p>Username: <%= user.username %></p>
       <p>Name :<%= user.displayName %></p>
<% } %>


In the above file we are managing log in button or profile data after login.  Follow the steps provided in the read.me file and run the app with url http://localhost:3000.

If still facing issue to run it. Write us at demo.jsonworld@gmail.com


You can download complete code from here. Download Code