WhatsApp DM Us 🇮🇳 +91-(120)-4137067 🇺🇸 +1-(315) 215-3533
Clixlogix
About
About
Why Clixlogix
Why fast-growing brands trust Clixlogix for digital success.
How We Work
Focused but flexible, explore our agile & collaborative approach.
Culture & Diversity
We bring diverse people together to drive growth-oriented culture.
Client Security
See how we ensure your intellectual property safety to protect you.
Our Team
Make some noise for our talented team powering your digital journey!
Partnership
Looking for a true end-to-end partner to drive growth?
Mission, Vision & Values
The fuel! What keeps us going?
Reviews & Testimonials
Clients love us. We stay humble. See what they have to say?
Know More About Us
Case Studies
Services
Services
All Services
One partner for all things AI & digital.
Digital Engineering
Custom web, mobile, cloud. Precision at AI assisted velocity.
Digital Marketing
AI assisted acquisition that earns its budget.
AI & ML
Agents, models, and RAG built for growth and production load.
QA & Testing
AI Assisted testing & defect catching before you ship.
Enterprise Software
Faster close, cleaner data, lower ops cost.
Creative & Design
Higher conversion, stronger recall, less friction.
Emerging Technologies
Blockchain, IoT, AR, and edge systems your roadmap can absorb.
Consulting Service
Defensible roadmaps, lower risk, sharper ROI math.
More About Services
Solutions
Solutions
Agritech
Intelligent farm management built for real acreage.
Fintech
Payments, lending, and wallets that clear an audit.
Video Calling
Scalable, crisp video calling built for real load.
Grocery Delivery
Lightning fast grocery delivery that scales cleanly.
E-Learning
Teaching and assessment with AI in the loop.
Telehealth
Secure patient care with AI for predictive outcomes.
Fitness Tracking
Goal tracking and coaching that keeps clients active.
EV Charging
Charging networks with reliability and predictive AI.
IoT & Automation
Connected automation with near zero defects on site.
View All Solutions
Industries
Industries
Agriculture
Smart farming and supply chain tech built for scale.
Automotive & Mobility
Connected vehicle and mobility software that scales.
Energy
Grid, asset, and consumption software for providers.
Finance
Secure, compliant fintech for regulated markets.
Healthcare
HIPAA ready software for providers and health tech.
Manufacturing
Industry 4.0 systems linking shop floor to decisions.
Real Estate
Property management and PropTech built for scale.
Retail
Omnichannel commerce and inventory for modern retail.
Travel & Leisure
Booking and guest experience for travel brands.
View All Industries
Careers
Blogs
Contact Us
  • View all About › Why ClixlogixHow We WorkCulture & DiversityClient SecurityOur TeamPartnershipMission, Vision & ValuesReviews & Testimonials
  • Case Studies ›
  • View all Services › Digital EngineeringDigital MarketingAI & MLQA & TestingEnterprise SoftwareCreative & DesignEmerging TechnologiesConsulting Service
  • View all Solutions › AgritechFintechVideo CallingGrocery DeliveryE-LearningTelehealthFitness TrackingEV ChargingIoT & Automation
  • View all Industries › AgricultureAutomotive & MobilityEnergyFinanceHealthcareManufacturingReal EstateRetailTravel & Leisure
  • Careers ›
  • Blogs ›
  • Contact Us ›
Contact Us →
WhatsApp Us Call Us
Clixlogix
  • About
    • Why Clixlogix
    • How We Work
    • Culture & Diversity
    • Client Security
    • Our Team
    • Partnership
    • Mission, Vision & Values
    • Reviews & Testimonials
  • Case Studies
  • Services
    • Digital Engineering
    • Digital Marketing
    • AI & ML
    • QA & Testing
    • Enterprise Software
    • Creative & Design
    • Emerging Technologies
    • Consulting Service
  • Solutions
    • Agritech
    • Fintech
    • Video Calling
    • Grocery Delivery
    • E-Learning
    • Telehealth
    • Fitness Tracking
    • EV Charging
    • IoT & Automation
  • Industries
    • Agriculture
    • Automotive & Mobility
    • Energy
    • Finance
    • Healthcare
    • Manufacturing
    • Real Estate
    • Retail
    • Travel & Leisure
  • Careers
  • Blogs
  • Contact Us
We are available 24/ 7. Call Now.

+1-315-215-3533

info@clixlogix.com

Contact information

c-84, sector 65, Noida

  • Home
  • Digital Engineering
  • Setting Up Passport.js for Eas ...
Shape Images
  • Home /
  • Blog /
  • Setting Up Passport.js for Easy Node.js User Authentication
Home / Blogs / Digital Engineering / Setting Up Passport.js for Easy Node.js User Authentication

Setting Up Passport.js for Easy Node.js User Authentication

Setting Up Passport.js for Easy Node.js User Authentication
by Editor Team April 6, 2017 7 min read
Share
Setting Up Passport.js for Easy Node.js User Authentication

Since its launch in early 2010s, NodeJS has rapidly changed the way in which web applications are being developed. It, thus, doesn’t come as a surprise that several top names in innovation, media and technology employ NodeJS as the mainstay of their backend computing.

What makes NodeJS a hot property in the developer community is the fact that it enables rapid development of complex user-centric web applications that can easily handle large amount of concurrent data being processed. This has been a key factor in why NodeJS is the building block of several popular applications that you might be using daily such as Netflix, Uber, PayPal among others. In our earlier blogs, we had pointed out in detail why NodeJS is a power to be reckoned with.

One thing to notice in the above list is that almost all of these applications are highly user-centric and hence involves users creating accounts on the application and sharing their personal and/or contact information. With that point, concerns about user privacy and users authentication are natural to crop up.

After years of absence of a single unifying authentication system, the developer community has just found the answer to all their prayers – Passport JS.

Power of Passport.js

Passport.js acts as the authentication middleware for Node.js. It is extremely flexible and modular in the sense that it can be unobtrusively dropped in to any express-based web application.

Passport.js’s sole purpose is to authenticate requests, which it does through an extensible set of plugins known as strategies. It offers more than 300 authentication strategies to support authentication using a username & password, twitter, facebook, and more.

Over the years, we have developed several applications based on NodeJS and have thus gained high level expertise in leveraging the goodness of Passport JS to make user authentication a seamless process.

We recently developed an eCommerce store for a Fortune500 Fashion brand and are glad to share how we incorporated Passport JS into the application.

Let’s Get Started with Installing Passport.js
> Installing Passport.js
Begin with installing Passport.js via NPM in your application.

$ npm install passport

Now since we are using facebook and twitter strategies as well, let’s install local plugin for local authentication as well as their plugins.

$ npm install passport-local
$ npm install passport-facebook

And then:

passport = require("passport");
LocalStrategy = require('passport-local').Strategy;
FacebookStrategy = require('passport-facebook').Strategy;

Adding passport middleware
Next up, you will have to make sure that this middleware is in use.

app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.session({ secret: 'SECRET' }));
app.use(passport.initialize());
app.use(passport.session());

Database and Models
Now we used mongoose to apply MongoDB serve in our web application

  1. Initiate MongoDB server by this code
    Mongod
  2. Using below code connect application to mongoDB server
    mongoose.connect("mongodb://localhost/myapp");
  3. Define the scheme for the application for local authentication
    var LocalUserSchema = new mongoose.Schema({
    username: String,
    salt: String,
    hash: String
    });
    var Users = mongoose.model('userauths', localUserSchema);
  4. Define facebook users schema and model to access and store information of the users logged in via facebook
    var FacebookUserSchema = new mongoose.Schema({
        fbId: String,
        email: { type : String , lowercase : true},
        name : String
    });
    var FbUsers = mongoose.model('fbs',FacebookUserSchema);

Strategies
Next we need to set the strategies to be initialized using passport initialize middleware.
Local Strategy

passport.use(new LocalStrategy(function(username, password,done){
    Users.findOne({ username : username},function(err,user){
        if(err) { return done(err); }
        if(!user){
            return done(null, false, { message: 'Incorrect username.' });
        }
        hash( password, user.salt, function (err, hash) {
            if (err) { return done(err); }
            if (hash == user.hash) return done(null, user);
            done(null, false, { message: 'Incorrect password.' });
        });
    });
}));

Facebook

First, you need to register a new application at Facebook Developers to get clientID and ClientSecret.

Kindly note that since we are running this application locally so we need to set up URL to http://localhost:3000. Also in callbackURL we passed the “/auth/facebook/callback” route at the end of the address because the authentication data would send to this route to connect to Facebook.

passport.use(new FacebookStrategy({
    clientID: "YOUR ID",
    clientSecret: "YOUR CODE",
    callbackURL: "http://localhost:3000/auth/facebook/callback"
  },
  function(accessToken, refreshToken, profile, done) {
    FbUsers.findOne({fbId : profile.id}, function(err, oldUser){
        if(oldUser){
            done(null,oldUser);
        }else{
            var newUser = new FbUsers({
                fbId : profile.id ,
                email : profile.emails[0].value,
                name : profile.displayName
            }).save(function(err,newUser){
                if(err) throw err;
                done(null, newUser);
            });
        }
    });
  }
));

Another important aspect of configuring passport is searlizeUser and DesearlizeUser, which basically enables the user to req.user and establish a secure session via a cookie set is the user’s browser.

passport.serializeUser(function(user, done) {
    done(null, user.id);
});
passport.deserializeUser(function(id, done) {
    FbUsers.findById(id,function(err,user){
        if(err) done(err);
        if(user){
            done(null,user);
        }else{
            Users.findById(id, function(err,user){
                if(err) done(err);
                done(null,user);
            });
        }
    });
});

In deserializeUser we basically locate a user in the database based on the provided id by facebook and pass the result to done().

Function Handlers

Here we have 2 helper functions. One to check if the user is already registered and logged in to the application and if so redirect to the previous session and if not registered, the user is redirected to sign up process.

function authenticatedOrNot(req, res, next){
    if(req.isAuthenticated()){
        next();
    }else{
        res.redirect("/login");
    }
}
function userExist(req, res, next) {
    Users.count({
        username: req.body.username
    }, function (err, count) {
        if (count === 0) {
            next();
        } else {
            // req.session.error = "User Exist"
            res.redirect("/singup");
        }
    });
}

Routes

The routes in themselves are quite easy to configure.

First, We need to define the user routes once he decides to sign up via facebook. We post request to “/signup” using passport built in login method which will automatically redirect the user to the designated screen.

Second, we also define the alternate route in case of a failed login process.

app.get("/auth/facebook", passport.authenticate("facebook",{ scope : "email"}));
app.get("/auth/facebook/callback",
    passport.authenticate("facebook",{ failureRedirect: '/login'}),
    function(req,res){
        res.render("loggedin", {user : req.user});
    }
);

It uses passport.authenticate() method to pass via facebook strategy.

Third, If we don’t use facebook or etc for signing in process and the user simply fills in the login form in “/login” route, it will send a post request to “/login” which in turn will be verified and authenticated by passing “local” as a first argument of passport.authenticate()method. Also there is some options like successRedirect, failureRedirect.

And lastly, passport have a built in logout() method that instead of destroying session like what we did before, we can use req.logout() on our “/logout” route.

Winding Up

Passport.js has proved to be instrumental in enabling developers to make good use of NodeJS and to continue developing robust user-centric applications that make this world a better place.

By providing itself as the middleware really, Passport JS makes the job of developers easier by providing an easy and quick way of taking care of the user privacy and authentication paradigms.

If you are a developer or just someone looking to have a NodeJS web application developed, we will be more than happy to help you in case you are stuck somewhere. Or if you just want to share your experience of working on NodeJS and PassportJS.

Share this blog

Summarise this with AI Open this article in your AI assistant with a summary prompt ready to send.
Claude ChatGPT Gemini Copilot Perplexity Grok

Written By

Editorial Team @ Clixlogix

Clixlogix Team is the collective voice of our engineering, design, marketing, and delivery practice. We write about the

Just Drop Us A Line

We are here to answer your questions 24/7

File should not exceed more than 20MB
🔒 SECURE SSL ENCRYPTION

Related blogs

Which B2B E-commerce Platform Fits Your Wholesale Model Best
Digital Engineering Oct 8, 2026

Which B2B E-commerce Platform Fits Your Wholesale Model Best

33 Hits READ MORE
Zero Latency Voice AI Agents for Operations Teams with Gemini 3.8 Live
Digital Engineering Oct 6, 2026

Zero Latency Voice AI Agents for Operations Teams with Gemini 3.8 Live

63 Hits READ MORE
What AI Code Generation Can and Cannot Do in 2026
Digital Engineering Oct 6, 2026

What AI Code Generation Can and Cannot Do in 2026

78 Hits READ MORE
Company
  • About Us
  • Our Team
  • How We Work
  • Culture & Diversity
  • Mission, Vision & Values
  • Security & Compliance
Explore
  • Case Studies
  • Solutions
  • Reviews
  • Partner With Us
  • Careers
  • Contact Us
  • Blogs
  • Latest Zoho Updates
Services
  • AI Software Development
  • AI Eval Framework
  • Vibe Coding Development
  • Vibe Coding Cleanup
  • ERP Services
  • CRM Services
  • Zoho Services
  • Zoho Consulting
  • Low Code Development
  • SEO Services
  • SEO Reseller
  • SEO Guarantee
  • Marketing Automation
  • AI Video Production
  • All Services
Industries
  • Healthcare
  • Banking & FinTech
  • Retail
  • Manufacturing
  • Energy & Utilities
  • Automotive
  • Real Estate
  • Agriculture
  • Beauty & Wellness
  • Sports & Fitness
  • All Industries
Follow Us
  • 12,272 Likes
  • 2,831 Followers
  • 4.2 Rated on Google
  • 22,526 Followers
  • 4.5 Rated on Clutch
© 2026 Clixlogix Technologies Pvt. Ltd. All rights reserved. DMCA Protected GSTIN : 09AAECC5421E1ZZ CIN : U74140UP2011PTC129448
Privacy PolicyTerms of ServiceSitemapRefund PolicyDelivery PolicyDisclaimer