Explain Passport in Node.js?

Passport is a popular Node.js authentication middleware that provides flexible authentication strategies. It handles user authentication, password encryption, and session management with minimal code complexity.

Passport offers over 500 authentication strategies including local authentication, OAuth (Google, Facebook), JWT tokens, and more. It integrates seamlessly with Express.js and popular databases like MongoDB.

Key Features

Authentication Strategies: Passport supports multiple authentication methods through strategy plugins. The most common is passport-local for username/password authentication.

Password Security: Automatically handles password hashing and verification using secure algorithms, protecting user credentials from being stored in plain text.

Session Management: Maintains user sessions using cookies, allowing users to stay logged in across page visits without repeated authentication.

Installation and Setup

Create a new Node.js project and install required packages:

npm init -y
npm install express mongoose passport passport-local passport-local-mongoose express-session body-parser

Basic Server Configuration

const express = require('express');
const mongoose = require('mongoose');
const session = require('express-session');
const passport = require('passport');
const passportLocalMongoose = require('passport-local-mongoose');

const app = express();

// Middleware setup
app.use(express.urlencoded({ extended: true }));
app.use(session({
    secret: 'your-secret-key',
    resave: false,
    saveUninitialized: false
}));

app.use(passport.initialize());
app.use(passport.session());

User Schema and Model

// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/passport-demo');

// User schema
const userSchema = new mongoose.Schema({
    email: String,
    password: String
});

// Add passport-local-mongoose plugin
userSchema.plugin(passportLocalMongoose);

const User = mongoose.model('User', userSchema);

// Configure passport
passport.use(User.createStrategy());
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());

Registration Form

Create register.html:

<!DOCTYPE html>
<html>
<head>
    <title>Register</title>
</head>
<body>
    <h2>User Registration</h2>
    <form action="/register" method="post">
        <input type="email" name="username" placeholder="Email" required>
        <br><br>
        <input type="password" name="password" placeholder="Password" required>
        <br><br>
        <button type="submit">Register</button>
    </form>
    <p><a href="/login">Already have an account? Login</a></p>
</body>
</html>

Login Form

Create login.html:

<!DOCTYPE html>
<html>
<head>
    <title>Login</title>
</head>
<body>
    <h2>User Login</h2>
    <form action="/login" method="post">
        <input type="email" name="username" placeholder="Email" required>
        <br><br>
        <input type="password" name="password" placeholder="Password" required>
        <br><br>
        <button type="submit">Login</button>
    </form>
    <p><a href="/">Don't have an account? Register</a></p>
</body>
</html>

Route Handlers

// Home route - serve registration form
app.get('/', (req, res) => {
    if (req.isAuthenticated()) {
        res.send('Welcome! You are logged in.');
    } else {
        res.sendFile(__dirname + '/register.html');
    }
});

// Login route
app.get('/login', (req, res) => {
    if (req.isAuthenticated()) {
        res.send('Already logged in!');
    } else {
        res.sendFile(__dirname + '/login.html');
    }
});

// Register POST route
app.post('/register', (req, res) => {
    User.register(
        { username: req.body.username }, 
        req.body.password, 
        (err, user) => {
            if (err) {
                console.log(err);
                res.redirect('/');
            } else {
                passport.authenticate('local')(req, res, () => {
                    res.send('Registration successful! You are now logged in.');
                });
            }
        }
    );
});

// Login POST route
app.post('/login', (req, res) => {
    const user = new User({
        username: req.body.username,
        password: req.body.password
    });

    req.login(user, (err) => {
        if (err) {
            console.log(err);
            res.redirect('/login');
        } else {
            passport.authenticate('local')(req, res, () => {
                res.send('Login successful! Welcome back.');
            });
        }
    });
});

// Logout route
app.get('/logout', (req, res) => {
    req.logout((err) => {
        if (err) {
            console.log(err);
        }
        res.redirect('/');
    });
});

app.listen(3000, () => {
    console.log('Server running on port 3000');
});

Authentication Middleware

The req.isAuthenticated() method checks if a user is logged in. You can create custom middleware for protected routes:

function requireAuth(req, res, next) {
    if (req.isAuthenticated()) {
        next();
    } else {
        res.redirect('/login');
    }
}

// Protected route example
app.get('/dashboard', requireAuth, (req, res) => {
    res.send('Dashboard - Only for authenticated users');
});

Running the Application

Start the server:

node server.js

Visit http://localhost:3000 to test registration and login functionality.

Security Benefits

Feature Benefit
Password Hashing Passwords stored securely, not in plain text
Session Management Secure user sessions with configurable expiration
Strategy Pattern Easy to switch between authentication methods
Middleware Integration Seamless integration with Express.js applications

Conclusion

Passport simplifies authentication in Node.js applications by providing secure password handling, flexible authentication strategies, and session management. It's the standard choice for implementing authentication in Express.js applications.

Updated on: 2026-03-15T23:19:00+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements