With Passport in an Express app, what do passport.use(), a strategy such as passport-local and its verify callback each do during a password login?
answer
- one interface, many credential types
- register by name, run by name
- strategy extracts, verify resolves
- username, password, done
basics
~20 spassport.use() registers a strategy under a name and passport.authenticate('local') runs it on a route. The strategy pulls credentials out of the request; your verify callback looks the user up and reports the outcome through done().
solid answer
~40 sPassport only authenticates requests: it mounts no routes and assumes no user schema. You register a strategy with `passport.use(new LocalStrategy(verify))`, which files it under the strategy's own name, `'local'`, unless you pass one as in `passport.use('password', ...)`. On the login route, `passport.authenticate('local', { failureRedirect: '/login' })` runs that strategy for the request. passport-local reads `username` and `password` from `req.body` (falling back to `req.query`), so a body parser such as `express.urlencoded()` has to run first. It then calls your `verify(username, password, done)`. Your code checks the password against your own store and calls `done(null, user)`, `done(null, false, info)` or `done(err)`, and Passport turns that into a login, a failure response or `next(err)`.
code
javascript · 23 linesconst express = require('express');
const passport = require('passport');
const LocalStrategy = require('passport-local');
const { findUserByUsername, passwordMatches } = require('./users');
passport.use(new LocalStrategy(async (username, password, done) => {
let user;
try {
user = await findUserByUsername(username);
if (user && !(await passwordMatches(user, password))) user = null;
} catch (err) {
return done(err);
}
if (!user) return done(null, false, { message: 'Incorrect username or password.' });
return done(null, user);
}));
const app = express();
app.post('/login',
express.urlencoded(),
passport.authenticate('local', { failureRedirect: '/login' }),
(req, res) => res.redirect('/')
);go deeper
Name the three pieces: passport.use registers a strategy by name, the strategy reads credentials, and your verify callback finds the user and calls done.
Explain the registry: default strategy names, overriding a name, and why a missing body parser makes passport-local answer 400 before your code runs.
Show that the verify callback owns the outage-versus-bad-password distinction, and that the strategy also accepts credentials from the query string, which you may want to refuse.
Frame Passport as a thin contract the team owns end to end: user storage, hashing and error semantics are all yours, which is both its flexibility and its cost.
## What Passport is, and what it is not **Passport** is authentication middleware for Express (and any Connect-style framework). Its README states its whole job: authenticate requests through an extensible set of plugins called **strategies**. It does not mount routes, it does not create a users table, and it does not decide what a user record looks like. Those decisions stay with the application, which is why the same Passport code works whether users live in a relational table, a document store or a directory service. That design gives every Passport login the same three moving parts, whatever the credential is. | Piece | Who writes it | What it does | |---|---|---| | **Strategy** | a package such as `passport-local` | extracts credentials from the request and drives the protocol | | **Verify callback** | you | turns those credentials into one of your users, or a refusal | | **`passport.authenticate()`** | Passport | runs the strategy on a route and acts on the outcome | ## Registering a strategy with `passport.use()` `passport.use()` stores a strategy instance in Passport's registry under a name: - With one argument, the name comes from the strategy itself: `passport-local` names itself `'local'`, `passport-openidconnect` `'openidconnect'`, the Google OAuth 2.0 strategy `'google'`. - With two arguments, `passport.use('password', new LocalStrategy(verify))`, your name overrides it, which is how one app registers two strategies of the same type. - A strategy with no name at all makes `passport.use()` throw `Authentication strategies must have a name`. - Asking `passport.authenticate()` for a name that was never registered does not fail quietly: the middleware calls `next()` with an `Unknown authentication strategy` error, so the request reaches your error handler. Registration happens once, at startup. The name is the only link between the route and the strategy. ## What `passport-local` does on each request When a route runs `passport.authenticate('local')`, the local strategy works through these steps: 1. It reads the username and password fields, named `username` and `password` by default and changed with the `usernameField` and `passwordField` options. 2. It looks for them in `req.body` first and then in `req.query`, so credentials in a query string are accepted too. 3. If either is missing it fails straight away with the message `Missing credentials` and status **400**, without calling your code. 4. Otherwise it calls your **verify callback**, `verify(username, password, done)`, or `verify(req, username, password, done)` when `passReqToCallback: true` is set. 5. Your callback finds the user, checks the password hash, and calls `done`. Step 3 explains a common first-day bug: if no body parser has run, the strategy sees no fields at all and every login answers **400 Bad Request**. Mount `express.urlencoded()` for an HTML form, or `express.json()` for a JSON body, on the login route or before it. ## The verify callback is the only part you own The verify callback is where your application's knowledge lives. Passport has no idea how passwords are hashed or where users are stored; the callback does. Its contract is the `done` function: - `done(null, user)` means the credentials are good and this is the user. - `done(null, false, { message })` means the credentials are wrong; the `info` object carries a message the failure handling can show. - `done(err)` means something broke, such as the database being unreachable, and is not the same thing as a wrong password. What Passport does with each of those outcomes (the default 401, `failureRedirect`, the error path) is the next layer down, and the same contract is repeated by every strategy, which is what makes them interchangeable. ## Putting it on a route The login route mounts a body parser, then `passport.authenticate()`, then the handler that runs only on success: ```js app.post('/login', express.urlencoded(), passport.authenticate('local', { failureRedirect: '/login' }), (req, res) => res.redirect('/') ); ``` Passport 0.6 and later attach `req.login` and friends inside `authenticate()` itself, so `app.use(passport.initialize())` is typically no longer needed, though older tutorials still show it. Keeping the user signed in across requests needs Passport's session support, which is a separate step covered with Passport's session mode. ## Mistakes worth recognising - Doing the password check inside the route handler after `passport.authenticate()`: by then the strategy has already decided. - Calling `done(null, false)` when the database throws, which reports an outage as a wrong password. - Forgetting the body parser and chasing a mysterious 400 from the login form. - Assuming a strategy handles user storage; it never does.
- Your login form posts email and pass instead of username and password. What changes?Pass the field names to the strategy: `new LocalStrategy({ usernameField: 'email', passwordField: 'pass' }, verify)`. The verify callback still receives them as its first two arguments; only the lookup in `req.body` changes. Without the options the strategy finds neither field and fails every attempt with `Missing credentials` and a 400.
- How do you register two local strategies, one for staff and one for customers, in the same app?Give each its own name with the two-argument form: `passport.use('staff-local', new LocalStrategy(verifyStaff))` and `passport.use('customer-local', new LocalStrategy(verifyCustomer))`. Each route then calls `passport.authenticate('staff-local')` or `passport.authenticate('customer-local')`. With the one-argument form the second registration would replace the first, since both are named `'local'`.
Passport is the entrance to a venue and each strategy is a different ticket scanner, one for paper barcodes and one for phone wallets. Every scanner reads its own kind of ticket, then asks the same box office lookup, your verify callback, whose ticket it is. The lookup gives one of three answers: the system is down, the ticket is not valid, or here is the holder.
- Passport stores the users and checks the passwords for you
- The verify callback is where routes are registered
- A failed login is reported by throwing from the verify callback
- passport-local works without any body parser mounted
- Every app must call app.use(passport.initialize()) on current Passport