top of page

Facebook login script for Node.js using the passport-facebook library

Here is an example of a basic Facebook login script for Node.js using the passport-facebook library:




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

passport.use(new FacebookStrategy({
    clientID: 'YOUR_APP_ID',
    clientSecret: 'YOUR_APP_SECRET',
    callbackURL: 'http://localhost:3000/auth/facebook/callback'
  },
  function(accessToken, refreshToken, profile, cb) {
    // User.findOrCreate({ facebookId: profile.id }, function (err, user) {
    //   return cb(err, user);
    // });
    return cb(null, profile);
  }
));

const app = express();

app.use(passport.initialize());

app.get('/auth/facebook', passport.authenticate('facebook'));

app.get('/auth/facebook/callback', 
  passport.authenticate('facebook', { failureRedirect: '/login' }),
  function(req, res) {
    // Successful authentication, redirect home.
    res.redirect('/');
  });

app.listen(3000, () => {
    console.log('Server started on http://localhost:3000');
});

This script uses the passport-facebook library to handle the Facebook login flow. The client ID and client secret for your app can be found in the app's settings on the Facebook developer portal. Make sure to replace the placeholder values in the script with the actual values for your app.


This script uses a simple callback function that just returns the authenticated user's Facebook profile. In a real-world application, you would likely want to do something more complex with the profile data, such as storing it in a database.


Also, you need to register your app on facebook developer portal and configure the callback url and other details.





3 views0 comments

Recent Posts

See All

Web development is a constantly evolving field, and staying up-to-date with the latest tools and technologies can be a challenge. However, understanding what tools are available and which are most rel

bottom of page