Skip to Content

How to login with Facebook in node js?

How to login with Facebook in node js?

Logging in with Facebook is a common feature in many web applications today. It allows users to easily register and login to your site without having to create yet another account and password to remember.

In this tutorial, we’ll see how to add Facebook login to a Node.js app using Passport.js. We’ll cover:

  • Registering a Facebook App
  • Installing Passport.js
  • Configuring Passport to use Facebook
  • Adding Facebook login routes
  • Adding a login button
  • Testing the login flow

By the end, you’ll understand how OAuth 2.0 works and be able to integrate Facebook login into your own Node.js apps!

Register a Facebook App

To use Facebook login, you need to first register an app on Facebook to get an app ID and app secret. Here’s how:

1. Go to the Facebook Developers page and log in.

2. Click ‘+ Add a New App’ button on the top right.

3. Choose a display name for your app. This can be anything.

4. Choose a category for your app. Select Apps for Pages.

5. Click Create App ID. Read and accept Facebook’s policy.

6. On the new app page, copy down the App ID and App Secret. We’ll need these soon.

7. Click Settings > Basic from the left menu.

8. Under App Domains, add your website’s domain.

This tells Facebook which domain is allowed to use your app. For local development, use localhost.

That’s it! We now have an app setup on Facebook ready to use.

Install Passport.js

We’ll be using Passport.js to make implementing Facebook login much easier.

Passport is middleware for Node.js that makes authentication simple. With over 500 authentication strategies, Passport can connect to Facebook, Twitter, and 100s of other services.

For our app, we’ll be using the passport-facebook module.

Let’s install Passport and passport-facebook:

“`
npm install passport passport-facebook
“`

This will install both Passport and the Facebook OAuth 2.0 strategy.

Configure Passport

With Passport installed, we need to configure it for our app. This involves:

1. Telling Passport to use the Facebook strategy
2. Providing Passport our Facebook app credentials
3. Defining a callback function that verifies the user

Here is an example setup:

“`js
// config/passport.js

const passport = require(‘passport’)
const FacebookStrategy = require(‘passport-facebook’).Strategy

passport.use(new FacebookStrategy({
clientID: process.env.FACEBOOK_APP_ID,
clientSecret: process.env.FACEBOOK_APP_SECRET,
callbackURL: “/auth/facebook/callback”
},
function(accessToken, refreshToken, profile, done) {
// User authenticated!
return done(null, profile)
}));
“`

This code does a few things:

1. Loads Passport and the Facebook strategy
2. Calls passport.use() to tell Passport to use Facebook authentication
3. Passes our app credentials from Facebook
4. Defines a callback function that is called when authentication succeeds. This simply returns the user profile as authenticated.

Make sure to replace the clientID and clientSecret with your actual app credentials.

We also need to setup Passport with our Express app:

“`js
// app.js

const passport = require(‘passport’)
require(‘./config/passport’) // load passport config

// …

app.use(passport.initialize())
app.use(passport.session())
“`

This initializes Passport and connects the Passport session with the Express session.

Add Facebook Login Routes

With Passport configured, we can now add routes for Facebook authentication.

When the user clicks the Facebook login button, they will be redirected to Facebook. After approving access to our app, the user is redirected back to our site.

Here are the routes needed:

“`js
// routes.js

const passport = require(‘passport’)

// Login route
router.get(‘/auth/facebook’, passport.authenticate(‘facebook’))

// Facebook callback route
router.get(‘/auth/facebook/callback’,
passport.authenticate(‘facebook’, { failureRedirect: ‘/login’ }),
function(req, res) {
// Successful authentication, redirect home.
res.redirect(‘/’)
});
“`

The /auth/facebook route redirects to Facebook and kicks off the authentication process.

When Facebook redirects back, the callback route is hit. This will call passport.authenticate() to verify the user. If authentication fails, we redirect back to the login page.

Otherwise, the user is now logged in! We can redirect to the home page or user profile.

Add Login Button

With our routes in place, the final step is adding the Facebook login button. This will redirect to the /auth/facebook route when clicked.

Here’s simple HTML code for a login button:

“`html

Login with Facebook

“`

When placing the button on your site, make sure it’s on the login page or any page requiring authentication.

This button will now kick off the Facebook authentication process!

Conclusion

And that’s it! We have integrated Facebook authentication into our Node.js app using Passport.js.

Here are some key things we learned:

  • Register an app on Facebook Developers to get credentials
  • Install passport and passport-facebook modules
  • Configure Passport to use the Facebook strategy
  • Add routes for Facebook login and callbacks
  • Redirect to Facebook from the login page
  • Verify the user in the Passport callback

Facebook login is a great way to provide registration and authentication without forcing users to create yet another username and password.

For next steps, look into:

  • Saving user profiles to your database
  • Adding additional info to profiles like name and email
  • Supporting persistent login sessions
  • Enabling login with other providers like Google and Twitter

I hope you enjoyed this tutorial on implementing Facebook authentication with Node.js and Passport! Let me know if you have any other questions.