Express.js Passport.js: How to Authenticate Users with Passport
Aug 14,2026

Introduction

Authentication is one of the most common requirements in web applications.

For example, when a user logs into an application, we need to:

  1. Receive the username and password.

  2. Find the user.

  3. Verify the password.

  4. Authenticate the user.

  5. Remember the authenticated user.

  6. Protect private routes.

  7. Allow the user to log out.

We can implement all of this manually, but authentication can become complicated quickly.

This is where Passport.js can help.

In this article, we'll learn how to use Passport.js with Express.js to implement a simple username/password authentication system.

We'll cover:

  • What Passport.js is

  • How Passport works

  • Installing Passport

  • Passport strategies

  • Using passport-local

  • Configuring Passport

  • Serializing and deserializing users

  • Login authentication

  • Protecting routes

  • Logout

  • Complete working example


What Is Passport.js?

Passport.js is authentication middleware for Node.js.

It provides a common way to authenticate users in Node.js and Express.js applications.

Passport itself doesn't decide how users should authenticate.

Instead, it uses different authentication strategies.

For example:

Passport
   |
   +-- Local Strategy
   |
   +-- Google Strategy
   |
   +-- GitHub Strategy
   |
   +-- Facebook Strategy
   |
   +-- JWT Strategy
   |
   +-- Other strategies

This makes Passport flexible.

You can choose an authentication strategy based on your application's requirements.


What Is a Passport Strategy?

A strategy defines how Passport authenticates a user.

For example, if you want users to log in using:

Username + Password

you can use:

passport-local

If you want Google authentication, you can use a Google strategy.

For GitHub authentication, you can use a GitHub strategy.

So the basic idea is:

Passport
   |
   ↓
Authentication Strategy
   |
   ↓
Verify User
   |
   ↓
Authentication Result

Passport Local Strategy

For this article, we'll use the local strategy.

Install the required packages:

npm install passport passport-local express-session

We need:

  • passport — Passport authentication middleware

  • passport-local — username/password authentication strategy

  • express-session — maintains the authenticated user's session


Project Structure

For a simple example, we can use:

passport-demo/
│
├── server.js
├── package.json
└── .env

Later, in a real application, you would normally separate routes, controllers, services, models, and authentication configuration.


Step 1: Create Express Application

Let's start with a basic Express server.

const express = require("express");

const app = express();

app.use(express.json());
app.use(express.urlencoded({ extended: true }));

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

Step 2: Configure Session

Passport commonly works with sessions when you're building session-based authentication.

First, import express-session:

const session = require("express-session");

Then configure it:

app.use(
  session({
    secret: process.env.SESSION_SECRET || "development-secret",
    resave: false,
    saveUninitialized: false,
    cookie: {
      httpOnly: true,
      secure: false,
      sameSite: "lax",
      maxAge: 60 * 60 * 1000
    }
  })
);

The session middleware must be registered before Passport's session middleware.


Step 3: Initialize Passport

Import Passport:

const passport = require("passport");

Then initialize it:

app.use(passport.initialize());

If you're using session-based authentication, also add:

app.use(passport.session());

So the order becomes:

app.use(session({
  secret: process.env.SESSION_SECRET || "development-secret",
  resave: false,
  saveUninitialized: false
}));

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

The order is important.


Why Do We Need passport.initialize()?

This middleware initializes Passport for the Express application.

app.use(passport.initialize());

It allows Passport to handle authentication-related operations.

Without it, Passport won't be properly initialized.


Why Do We Need passport.session()?

If you're using session-based authentication, Passport needs to restore the authenticated user from the session on subsequent requests.

That's what:

app.use(passport.session());

does.

The complete flow is:

Request
   ↓
express-session
   ↓
passport.initialize()
   ↓
passport.session()
   ↓
Route

Step 4: Create a User

For this example, let's use a simple in-memory array.

In a real application, you would normally retrieve the user from a database.

const users = [
  {
    id: 1,
    username: "john",
    password: "123456"
  },
  {
    id: 2,
    username: "sarah",
    password: "password123"
  }
];

This is only for demonstration.

Never store plain-text passwords like this in a real application.

In production, passwords should be securely hashed using a password hashing library such as bcrypt.


Step 5: Configure Local Strategy

Import LocalStrategy:

const LocalStrategy = require("passport-local").Strategy;

Now configure it:

passport.use(
  new LocalStrategy((username, password, done) => {
    const user = users.find(
      (user) => user.username === username
    );

    if (!user) {
      return done(null, false, {
        message: "User not found"
      });
    }

    if (user.password !== password) {
      return done(null, false, {
        message: "Incorrect password"
      });
    }

    return done(null, user);
  })
);

Let's understand what's happening here.


How LocalStrategy Works

When the user submits:

username
password

Passport passes them to the strategy:

(username, password, done)

We find the user:

const user = users.find(
  (user) => user.username === username
);

If the user doesn't exist:

return done(null, false);

If the password is incorrect:

return done(null, false);

If authentication succeeds:

return done(null, user);

Understanding done()

The done() callback is an important part of Passport strategies.

The general format is:

done(error, user, info)

For example:

done(null, user);

means authentication was successful.

This:

done(null, false);

means authentication failed.

And:

done(error);

means an error occurred.

You can also provide additional information:

done(null, false, {
  message: "Invalid username or password"
});

Step 6: Serialize the User

When authentication succeeds, Passport needs to determine what information should be stored in the session.

We do this using:

passport.serializeUser()

Example:

passport.serializeUser((user, done) => {
  done(null, user.id);
});

Here we're storing only:

user.id

in the session.

For example:

Session
{
  passport: {
    user: 1
  }
}

We don't need to store the entire user object.


Step 7: Deserialize the User

When the user makes another request, Passport needs to convert the stored ID back into a user object.

We use:

passport.deserializeUser()

Example:

passport.deserializeUser((id, done) => {
  const user = users.find(
    (user) => user.id === id
  );

  done(null, user);
});

The flow becomes:

Login
  ↓
User authenticated
  ↓
serializeUser()
  ↓
Store user ID in session
  ↓
Next request
  ↓
deserializeUser()
  ↓
Find user
  ↓
req.user

Step 8: Create Login Route

Now we can create a login route.

app.post(
  "/login",
  passport.authenticate("local", {
    failureMessage: true
  }),
  (req, res) => {
    res.json({
      message: "Login successful",
      user: req.user
    });
  }
);

Here:

passport.authenticate("local")

tells Passport to use the local strategy.


What Happens During Login?

Suppose the client sends:

POST /login

with:

{
  "username": "john",
  "password": "123456"
}

The flow is:

POST /login
      ↓
passport.authenticate("local")
      ↓
LocalStrategy
      ↓
Find user
      ↓
Verify password
      ↓
Authentication successful
      ↓
serializeUser()
      ↓
Store user ID in session
      ↓
req.user
      ↓
Login successful

Step 9: Access req.user

After successful authentication, Passport makes the authenticated user available through:

req.user

For example:

app.get("/profile", (req, res) => {
  res.json({
    user: req.user
  });
});

If the user is authenticated, you might receive:

{
  "user": {
    "id": 1,
    "username": "john",
    "password": "123456"
  }
}

However, in a real application, never send password hashes or passwords back to the client.

The example contains the password only because we're using a simple in-memory object for demonstration.


Step 10: Protect Routes

Passport provides a useful middleware:

passport.authenticate("local")

for authentication.

But after login, we usually need to check whether the user is already authenticated.

Passport provides:

req.isAuthenticated()

Example:

app.get("/profile", (req, res) => {
  if (!req.isAuthenticated()) {
    return res.status(401).json({
      message: "Please login first"
    });
  }

  res.json({
    message: "Welcome to your profile",
    user: req.user
  });
});

If the user isn't authenticated:

{
  "message": "Please login first"
}

Creating an Authentication Middleware

Instead of repeating:

if (!req.isAuthenticated()) {
  return res.status(401).json({
    message: "Please login first"
  });
}

we can create middleware.

const isAuthenticated = (req, res, next) => {
  if (req.isAuthenticated()) {
    return next();
  }

  res.status(401).json({
    message: "Please login first"
  });
};

Now we can use it on any protected route:

app.get("/profile", isAuthenticated, (req, res) => {
  res.json({
    message: "Welcome to your profile",
    user: req.user
  });
});

This makes the code cleaner and easier to maintain.


Logout

Passport provides:

req.logout()

for logging out a user.

Example:

app.post("/logout", (req, res) => {
  req.logout((err) => {
    if (err) {
      return res.status(500).json({
        message: "Logout failed"
      });
    }

    res.json({
      message: "Logout successful"
    });
  });
});

After logout, the authenticated user is removed from the Passport session.


Complete Example

Here's the complete example in one file.

const express = require("express");
const session = require("express-session");
const passport = require("passport");
const LocalStrategy = require("passport-local").Strategy;

const app = express();

app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// Session configuration
app.use(
  session({
    secret: process.env.SESSION_SECRET || "development-secret",
    resave: false,
    saveUninitialized: false,
    cookie: {
      httpOnly: true,
      secure: false,
      sameSite: "lax",
      maxAge: 60 * 60 * 1000
    }
  })
);

// Initialize Passport
app.use(passport.initialize());
app.use(passport.session());

// Example users
const users = [
  {
    id: 1,
    username: "john",
    password: "123456"
  },
  {
    id: 2,
    username: "sarah",
    password: "password123"
  }
];

// Local Strategy
passport.use(
  new LocalStrategy((username, password, done) => {
    const user = users.find(
      (user) => user.username === username
    );

    if (!user) {
      return done(null, false, {
        message: "User not found"
      });
    }

    if (user.password !== password) {
      return done(null, false, {
        message: "Incorrect password"
      });
    }

    return done(null, user);
  })
);

// Serialize user
passport.serializeUser((user, done) => {
  done(null, user.id);
});

// Deserialize user
passport.deserializeUser((id, done) => {
  const user = users.find(
    (user) => user.id === id
  );

  done(null, user);
});

// Authentication middleware
const isAuthenticated = (req, res, next) => {
  if (req.isAuthenticated()) {
    return next();
  }

  res.status(401).json({
    message: "Please login first"
  });
};

// Login
app.post(
  "/login",
  passport.authenticate("local"),
  (req, res) => {
    res.json({
      message: "Login successful",
      user: {
        id: req.user.id,
        username: req.user.username
      }
    });
  }
);

// Protected profile route
app.get(
  "/profile",
  isAuthenticated,
  (req, res) => {
    res.json({
      message: "Welcome to your profile",
      user: {
        id: req.user.id,
        username: req.user.username
      }
    });
  }
);

// Logout
app.post("/logout", (req, res) => {
  req.logout((err) => {
    if (err) {
      return res.status(500).json({
        message: "Logout failed"
      });
    }

    res.json({
      message: "Logout successful"
    });
  });
});

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

Understanding the Complete Passport Flow

The complete authentication flow can be summarized as:

             LOGIN
                |
                v
        POST /login
                |
                v
 passport.authenticate("local")
                |
                v
         LocalStrategy
                |
                v
       Find the user
                |
                v
       Verify password
                |
          +-----+-----+
          |           |
       Failed       Success
          |           |
          v           v
      Reject      serializeUser()
                      |
                      v
                Store user ID
                   in session
                      |
                      v
                 req.user

For future requests:

Request
   |
   v
express-session
   |
   v
passport.session()
   |
   v
deserializeUser()
   |
   v
Find user
   |
   v
req.user
   |
   v
Protected Route

Where Does the User Come From?

In our example, users are stored in an array:

const users = [
  {
    id: 1,
    username: "john",
    password: "123456"
  }
];

But real applications normally use a database.

For example:

Client
   |
   v
Express API
   |
   v
Passport
   |
   v
Local Strategy
   |
   v
User Service
   |
   v
MongoDB / PostgreSQL / MySQL

The strategy can query the database:

passport.use(
  new LocalStrategy(async (username, password, done) => {
    // Find user from database
    // Compare password
    // Return authenticated user
  })
);

Password Hashing

The example above compares plain-text passwords:

if (user.password !== password)

This should never be used in a real application.

Passwords should be hashed before being stored in the database.

For example, using bcrypt:

npm install bcrypt

During registration:

const bcrypt = require("bcrypt");

const hashedPassword = await bcrypt.hash(password, 10);

Then store:

{
  username: "john",
  password: hashedPassword
}

During login, compare the password:

const isValid = await bcrypt.compare(
  password,
  user.password
);

This is the approach you should use in a production application.


Passport Without Sessions

Passport can also be used without sessions.

For example, JWT authentication commonly works without server-side sessions.

You can configure authentication like:

passport.authenticate("jwt", {
  session: false
});

The important part is:

session: false

This tells Passport not to create a login session.

For example:

app.get(
  "/profile",
  passport.authenticate("jwt", {
    session: false
  }),
  (req, res) => {
    res.json({
      user: req.user
    });
  }
);

So Passport isn't limited to session-based authentication.


Passport Strategies

One of Passport's biggest advantages is its strategy-based architecture.

Depending on your application, you can use different strategies.

Some common examples include:

Local
Google
GitHub
Facebook
JWT
OAuth

The strategy determines how the user is authenticated.

For example:

Username + Password
        ↓
Local Strategy

or:

Google Account
        ↓
Google Strategy

or:

JWT Token
        ↓
JWT Strategy

Passport vs Manual Authentication

Without Passport, you might write authentication logic manually:

Login API
   ↓
Find User
   ↓
Verify Password
   ↓
Create Session
   ↓
Store User
   ↓
Check Authentication
   ↓
Logout

Passport provides a structured way to handle authentication strategies and integrate them into Express.

This is especially useful when your application supports multiple authentication methods.


Common Beginner Mistakes

1. Forgetting passport.initialize()

You need:

app.use(passport.initialize());

2. Forgetting passport.session()

If you're using sessions, you also need:

app.use(passport.session());

3. Incorrect middleware order

Use:

app.use(session(...));

app.use(passport.initialize());

app.use(passport.session());

The session middleware should come before Passport's session middleware.


4. Forgetting serialization

For session-based authentication, you need:

passport.serializeUser(...)
passport.deserializeUser(...)

5. Returning passwords

Never return passwords or password hashes in API responses.

Instead:

res.json({
  id: req.user.id,
  username: req.user.username
});

6. Storing plain-text passwords

Never store:

password: "123456"

in a real database.

Use a secure password hashing algorithm such as bcrypt.


Final Thoughts

Passport.js provides a flexible authentication system for Node.js and Express.js applications.

The key concept to understand is that Passport itself doesn't define one authentication method. Instead, it uses strategies.

For username/password authentication, we can use:

npm install passport passport-local express-session

Then configure:

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

Create a local strategy:

passport.use(
  new LocalStrategy((username, password, done) => {
    // Find and verify user
  })
);

Serialize the user:

passport.serializeUser((user, done) => {
  done(null, user.id);
});

Deserialize the user:

passport.deserializeUser((id, done) => {
  // Find user
});

Authenticate during login:

passport.authenticate("local")

Check authentication:

req.isAuthenticated()

Access the authenticated user:

req.user

And log out:

req.logout()

Once you understand these pieces, Passport becomes much easier to work with.

The next logical step is to build a complete Express.js authentication API using Passport + MongoDB + bcrypt, including registration, login, protected routes, logout, and proper error handling.