Skip to content

What Passport.js Actually Does

Passport.js is extremely popular Express middleware that connects the tedious process of credential-checking to the Express request-response flow. It handles the mundane heavy lifting of maintaining logged-in states.

At a high conceptual level, Passport.js operates in three distinct phases:

  1. Strategy: The specific method of authentication (e.g., local username/password, Google OAuth, GitHub, etc.).
  2. Verify Callback: The custom function you write that checks those incoming credentials against your database and returns a user object.
  3. Session Management: The mechanism of serializing that user for storage in a session, and then deserializing it back into req.user on future requests.
Neo-Retro isometric conceptual diagram of a robot bouncer protecting a server rack.

Fig 1: The Bouncer (Passport), the Clipboard (Strategy), and the Club (Server)

Professor Solo: Think of Passport as the framework’s bouncer. It stands at the door with a clipboard (the Strategy) and asks for ID. If you check out (the Verify phase), it slaps a shiny wristband on you (the Session) cookie, so you can wander around freely without being carded at every single room.

It’s equally important to understand where Passport’s responsibilities end. Many beginners assume Passport is a magic bullet, only to realize it requires significant manual configuration.

Passport does not:

  • Create our database User model or schema.
  • Hash our passwords before saving them (we rely on bcrypt for that).
  • Create our session store infrastructure (we rely on express-session for that).
  • Decide which specific routes are “admin-only” (that’s Authorization, which we’ll define with middleware in the next lesson).

T.A. Watts Note: The most common point of failure is misunderstanding Serialize and Deserialize. Serializing is Passport extracting a unique identifier (like the user ID) from the authenticated user and storing it in the active session. Deserializing is Passport taking that stored ID on subsequent requests, retrieving the full User from the database, and attaching it to req.user.

With the theory out of the way, let’s install the actual dependencies.

Before we start wiring up the routes, let’s install the fundamental packages required for this stack. Run the following command in your terminal:

Terminal window
npm install passport passport-local express-session bcrypt
  • passport: The core authentication framework.
  • passport-local: The specific strategy for authenticating with a username (or email) and password.
  • express-session: Exposes the session object and manages the cookie exchange.
  • bcrypt: The encryption library we’ll use to securely hash user passwords.

Passport.js

Passport is hired, but what exactly do we expect it to do?