Node JS Express Passport Facebook Login Tutorial

Node js express facebook login using passport tutorial; i am going to show you how to integrate a facebook login authentication button in node js express using passport js.

Passport is authentication middleware for Node. js. As it’s extremely flexible and modular, Passport can be unobtrusively dropped into any Express-based web application. A comprehensive set of strategies supports authentication using a username and password, Facebook, Twitter, and more.

First of all visit this url https://developers.facebook.com/apps/ and create a new facebook app for your node js express passport facebook login app. After create facebook; you will find facebook secret id and secret key,Which is found from the Facebook Developer Console App.

Implement Facebook Login Authentication with Passport In Node JS Express

  • Step 1: Create New App & Install Require Modules
    • Create Node Express JS App Directory
    • Install Require Modules
  • Step 2: Import Installed Module and Routes in app.js
  • Step 3: Create views
  • Step 4: Create Config.js
  • Step 5: Start Development Server

Step 1: Create New App & Install Require Modules

Create Node Express JS App Directory

Execute the following command on terminal to create directory:

mkdir facebookAuth

Then open facebookAuth directory with any text editor. And use the following command to enter your facebookAuth app directories, So open your cmd and run the following command:

cd facebookAuth

Install Require Modules

Execute the following command on terminal to install express, ejs, express-session and passport:

npm install express ejs express-session passport passport-facebook-oauth --save
npm install
express-flash

Flash is an extension of connect-flash with the ability to define a flash message and render it without redirecting the request.
In this node js mysql crud tutorial express flash is used to display a warning, error and information message

express-session

Express-session is used to made a session as like in PHP. In this node js mysql crud tutorial, session is needed as the express requirement of express-flash.

EJS

To render HTML pages for login and profile

passport

Social Authentication package for Node.js

passport-facebook-oauth

Facebook authentication module by Passport.js

Step 2: Import Installed Module and Routes in app.js

Visit your node js express facebook login app and import installed modules and create routes in app.js file; as shown below:

const express = require('express');
const app = express();
const session = require('express-session');
const passport = require('passport');
const FacebookStrategy = require('passport-facebook').Strategy;
const indexRouter = require('./routes.js');
const config = require('./config')
app.set('view engine', 'ejs');
app.use(session({
  resave: false,
  saveUninitialized: true,
  secret: 'SECRET'
}));
app.use(passport.initialize());
app.use(passport.session());
passport.serializeUser(function (user, cb) {
  cb(null, user);
});
passport.deserializeUser(function (obj, cb) {
  cb(null, obj);
});
passport.use(new FacebookStrategy({
    clientID: config.facebookAuth.clientID,
    clientSecret: config.facebookAuth.clientSecret,
    callbackURL: config.facebookAuth.callbackURL
  }, function (accessToken, refreshToken, profile, done) {
    return done(null, profile);
  }
));
app.use('/', indexRouter);
const port = 3000;
app.listen(port, () => {
  console.log('App listening on port ' + port);
});

Create a file named routes.js into your app root directory and add the following routes in it:

const passport = require('passport');
const express = require('express');
var router = express.Router();
router.get('/', function (req, res) {
  res.render('pages/index.ejs'); // load the index.ejs file
});
router.get('/profile', isLoggedIn, function (req, res) {
  res.render('pages/profile.ejs', {
    user: req.user // get the user out of session and pass to template
  });
});
router.get('/error', isLoggedIn, function (req, res) {
  res.render('pages/error.ejs');
});
router.get('/auth/facebook', passport.authenticate('facebook', {
  scope: ['public_profile', 'email']
}));
router.get('/auth/facebook/callback',
  passport.authenticate('facebook', {
    successRedirect: '/profile',
    failureRedirect: '/error'
  }));
router.get('/logout', function (req, res) {
  req.logout();
  res.redirect('/');
});
function isLoggedIn(req, res, next) {
  if (req.isAuthenticated())
    return next();
  res.redirect('/');
}
module.exports = router;

Step 3: Create views

Create directory name pages. And inside the pages/ directory, you need to create two views file; as following:

  • index.ejs
  • profile.ejs

Visit views/pages directory and create index.ejs file. Then update the following code into your file:

<!doctype html>
<html>
<head>
  <title>Facebook Login Authentication in Node js Express - Laratutorials.com</title>
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
  <link rel="stylesheet" type="text/css"
    href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/css/materialize.min.css">
  <style>
    .facebook {
      background-color: #3b5998 !important;
      color: #fff !important;
    }
    .fa-facebook-f:before,
    .fa-facebook:before {
      content: "\f09a";
    }
  </style>
</head>
<body>
  <nav class="light-blue lighten-1" role="navigation">
    <div class="nav-wrapper container">
      <a id="logo-container" href="#" class="brand-logo">Node Authentication</a>
    </div>
  </nav>
  <div class="section no-pad-bot" id="index-banner">
    <div class="container">
      <br><br>
      <div class="row center">
        <div class="col s6 offset-s3">
          <div class="card">
            <div class="card-content">
              <span class="card-title">Facebook Login using Node and passport</span>
            </div>
            <div class="card-action">
              <a href="/auth/facebook" class="waves-effect waves-light btn social facebook">
                <i class="fa fa-facebook"></i> Sign in with facebook
              </a>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</body>
</html>

Visit views/pages directory and create profile.ejs file. Then update the following code into your file:

<!doctype html>
<html>
<head>  
  <title>Facebook Node Authentication</title>
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <link rel="stylesheet" type="text/css"
    href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/css/materialize.min.css">
  <style>
    .card:hover {
      box-shadow: 0 10px 20px rgba(0, 0, 0, 0.19), 0 6px 6px rgba(0, 0, 0, 0.23);
      margin-bottom: 54px;
    }
  </style>
</head>
<body>
  <nav class="light-blue lighten-1" role="navigation">
    <div class="nav-wrapper container">
      <a id="logo-container" href="#" class="brand-logo">Node Authentication</a>
      <a href="/logout" class="right">Logout</a>
    </div>
  </nav>
  <div class="section no-pad-bot" id="index-banner">
    <div class="container">
      <br><br>
      <div class="row center">
        <div class="col s12">
          <div class="card">
            <div class="card-content blue lighten-3">
              <span class="card-title white-text"><strong><i class="large material-icons">person</i>
                </strong></span>
            </div>
            <div class="card-action">
              <h5><b><%= user.displayName %></b></h5>
              <p><strong>Facebook id</strong>: <%= user.id %></p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</body>
</html>

Step 4: Create Config.js

Create config.js file in the root directory. Then add the following code into it:

module.exports = {
	'facebookAuth': {
		'clientID':  '<APP_ID>', // your App ID
		'clientSecret':  '<APP_SECRET>', // your App Secret
		'callbackURL':  'http://localhost:3000/auth/facebook/callback'
	}
}

Step 5: Start Development Server

Execute the following command on terminal to start node js facebook login with passport app development server:

//run the below command

npm start

after run this command open your browser and hit 

http://127.0.0.1:3000
OR
http://localhost:3000

Conclusion

Node express js facebook auth login example tutorial. You have learned how to create facebook authentication in node js express with passport.

Recommended Node Js Tutorials

Leave a Comment