Node JS Passport Login with Facebook Tutorial

Node js Facebook Login tutorial; Social login is genuinely helpful and makes user registration super easy. There are various types of social media websites such as Facebook, Twitter, GitHub, Gmail etc.

You can create a social login auth system using these social media sites. This comprehensive tutorial will teach you how to create Signin with Facebook in the Node js application using the Passport and express js.

We will need passport js to implement passport js authentication in Node js. Passport is authentication middleware for Node Js. Incredibly flexible and modular, Passport can be unobtrusively dropped into any Express-based web application.

Not just social media log in, but this comprehensive module comes with a set of strategies that supports authentication using a username and password.

Let us look at step by step, how to integrate sign in with facebook in node js.

How to Integrate Passport Js Login with Facebook in Node

  • Step 1: Set Up Node Project
  • Step 2: Get Facebook Credentials
  • Step 3: Install Dependencies
  • Step 4: Create Facebook Auth Views
  • Step 5: Set Up Auth Route
  • Step 6: Configure Server
  • Step 7: Run Application

Set Up Node Project

To set up the new node application, create an empty directory.

mkdir node-facebook-auth

Next, step inside the project folder using given command:

cd node-facebook-auth

Now, you have to create the package.json file and you can create it by using the following command.

npm init

Furthermore, you have to create the server.js file, and don’t forget to add it in the package.json file.

{
  "main": "server.js",
}

Get Facebook Credentials

Let us create the Facebook app id and app secret hence go to Facebook Developer page.

Step 1: Invoke the first step by clicking on the “Create App” button.

Facebook Create App

Step 2: Declare the app name and contact email and click on the Create App button.

Create an App modal

Step 3: Next, you have to look for a Facebook Login card, click on the Set-Up link.

Facebook list of product cards

Step 4: Now, you have to select the required platform, options are iOS, Android, Web, and Other options. We choose the Web option.

choose the platform

Step 5: You need to define the url of your app where you have to enable the Facebook login service.

For instance, we are working with localhost, therefore we added the localhost url.

add app url

Step 6: Now, you need to copy App ID and App Secret from Facebook developer dashboard.

Get Facebook APP SECRET and APP ID

Install Dependencies

Now, in this step you have to install express, passport, ejs, express-session, and passport-facebook packages.

npm install express passport ejs express-session passport-facebook

Next, you have to install nodemon library.

Nodemon module allows develop node js applications by automatically starting the node apps when detect changes in app files.

npm install nodemon --save-dev

Create Facebook Auth Views

In the next step, create a ‘views’ folder, then create following files and insert the provided code inside of it to manage the views of auth app:

Create and add given code into views/index.ejs file:

<!DOCTYPE html>
<html>
  <head>
    <title>Node Js Facebook Authentication Example</title>
    <link
      rel="stylesheet"
      href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"
    />
    <link
      href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
      rel="stylesheet"
    />
  </head>

  <body>
    <div class="container mt-5">
      <h2>Facebook Login using Node and Passport</h2>

      <div class="d-grid mt-3">
        <a href="/auth/facebook" class="btn btn-primary facebook-clr">
          <i class="fa fa-facebook"></i> Login with Facebook
        </a>
      </div>
    </div>
  </body>
</html>

Head over to the root of your project, create a config.js file, and place the given code into the file. Make sure to replace your Facebook app secret and app id.

module.exports = {
  facebookAuth: {
    clientID: '<FACEBOOK_APP_ID_GOES_HERE>',
    clientSecret: '<FACEBOOK_APP_SECRET_GOES_HERE>',
    callbackURL: 'http://localhost:4200/auth/facebook/callback',
  },
}

Set Up Auth Route

In this step, you will be creating routes for handling facebook login authentication views and requests.

Make sure to create auth-routes.js file and insert the following code into the file.

const express = require('express')
const passport = require('passport')

let router = express.Router()

router.get('/', function (req, res) {
  res.render('index.ejs')
})

router.get(
  '/auth/facebook',
  passport.authenticate('facebook', {
    scope: ['public_profile', 'email'],
  }),
)

router.get(
  '/auth/facebook/callback',
  passport.authenticate('facebook', {
    successRedirect: '/user-profile',
    failureRedirect: '/auth-error',
  }),
)

function isSignedIn(req, res, next) {
  if (req.isAuthenticated()) return next()
  res.redirect('/')
}

module.exports = router

Configure Server

In this step, we are going to set up the node server file. Mainly, we are going to configure routes, sessions, application connections etc. in this file.

Therefore open the server.js file and insert the given code into it.

const express = require('express')
const session = require('express-session')
const passport = require('passport')
const FacebookStrategy = require('passport-facebook').Strategy

const config = require('./config')
const authRoutes = require('./auth-routes.js')

const app = express()

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('/', authRoutes)

const port = 4200

app.listen(port, () => {
  console.log('App connected on port: ' + port)
})

Run Application

Type the given command on the terminal and invoke the command by pressing enter.

nodemon

Now, you can add the given url on the browser to check the node js facebook authentication system:

http://localhost:4200

Node JS Passport Login with Facebook Tutorial