What Passport.js Actually Does
The Bouncer at the Door
Section titled “The Bouncer at the Door”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:
- Strategy: The specific method of authentication (e.g., local username/password, Google OAuth, GitHub, etc.).
- Verify Callback: The custom function you write that checks those incoming credentials against your database and returns a user object.
- Session Management: The mechanism of serializing that user for storage in a session, and then deserializing it back into
req.useron future requests.
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.
What Passport DOES NOT Do
Section titled “What Passport DOES NOT Do”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
Usermodel or schema. - Hash our passwords before saving them (we rely on
bcryptfor that). - Create our session store infrastructure (we rely on
express-sessionfor 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.
Installation and Setup
Section titled “Installation and Setup”Before we start wiring up the routes, let’s install the fundamental packages required for this stack. Run the following command in your terminal:
npm install passport passport-local express-session bcryptpassport: 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.
Extra Bits & Bytes
Section titled “Extra Bits & Bytes”Passport.js
⏭ Next: Target Auth Behavior
Section titled “⏭ Next: Target Auth Behavior”Passport is hired, but what exactly do we expect it to do?