How to Implement Facebook Login using Node.js and Passport.js

Social media login options have become increasingly popular for websites and applications, providing users with a convenient way to log in without the hassle of creating new accounts. In this tutorial, we will explore how to implement Facebook login using Node.js and Passport.js, a powerful authentication library for Node.js.

Prerequisites

Before getting started, make sure you have the following installed on your machine:

  • Node.js: You can download it from the official website here.
  • NPM (Node Package Manager): This comes bundled with Node.js.

Setting Up the Project

  1. Please create a new directory for your project and navigate to it in your terminal.
  2. Initialize a new Node.js project by running npm init and following the prompts.
  3. Install the required dependencies by running the following command:
npm install express passport passport-facebook

Configuring the Application

Now, let’s create an Express.js server and configure Passport.js for Facebook login.

  1. Create a new file, app.js and require the necessary modules:
const express = require('express');
const passport = require('passport');
const FacebookStrategy = require('passport-facebook').Strategy;
  1. Initialize an Express application:
const app = express();
  1. Set up Passport.js middleware and configure the Facebook strategy. Replace 'YOUR_FACEBOOK_APP_ID' and 'YOUR_FACEBOOK_APP_SECRET' with your own Facebook App credentials:
passport.use(
  new FacebookStrategy(
    {
      clientID: 'YOUR_FACEBOOK_APP_ID',
      clientSecret: 'YOUR_FACEBOOK_APP_SECRET',
      callbackURL: '/auth/facebook/callback',
    },
    function (accessToken, refreshToken, profile, done) {
      // This function will be called when the user is authenticated
      // Handle user data and session management here
      // Example: store user data in session or database
      return done(null, profile);
    }
  )
);
  1. Set up Express routes:
app.get('/auth/facebook', passport.authenticate('facebook'));

app.get(
  '/auth/facebook/callback',
  passport.authenticate('facebook', {
    successRedirect: '/profile',
    failureRedirect: '/login',
  })
);

app.get('/profile', (req, res) => {
  // Access the authenticated user's data using req.user
  res.send(req.user);
});
  1. Start the server:
const port = 3000;
app.listen(port, () => {
  console.log(`Server running on port ${port}`);
});

Obtaining Facebook App Credentials

To enable Facebook login, you’ll need to obtain your Facebook App credentials:

  1. Go to the Facebook Developer Console and create a new app.
  2. Retrieve your Facebook App ID and App Secret.
  3. Add the callback URL (http://localhost:3000/auth/facebook/callback) to the app’s settings.

Running the Application

  1. In the terminal, navigate to the project directory.
  2. Run node app.js to start the server.
  3. Open a web browser and go to http://localhost:3000/auth/facebook initiate the Facebook login flow.

Conclusion

In this tutorial, we learned how to implement Facebook login using Node.js and Passport.js. By leveraging the Passport.js library and the Facebook Graph API, we were able to provide users with a seamless and secure login experience.

Remember to keep your Facebook App credentials secure and consider using environment variables to store sensitive information instead of hardcoding them in your code. You can customize the code to fit your specific needs, such as storing user data in a database or adding additional functionality.

Feel free to explore other authentication strategies supported by Passport.js, as it offers various options for integrating with different authentication providers.

You can find the complete source code for this tutorial on GitHub.

Happy coding!

Remember to replace 'YOUR_FACEBOOK_APP_ID' and 'YOUR_FACEBOOK_APP_SECRET' with your actual Facebook App credentials.

Feel free to modify and enhance the blog post as per your requirements.

Atiqur Rahman

I am MD. Atiqur Rahman graduated from BUET and is an AWS-certified solutions architect. I have successfully achieved 6 certifications from AWS including Cloud Practitioner, Solutions Architect, SysOps Administrator, and Developer Associate. I have more than 8 years of working experience as a DevOps engineer designing complex SAAS applications.

Leave a Reply