Skip to content
Tutorials Center
My learning

Topics

Lesson 91 of 133 ยท Frameworks and Ecosystem

Passport.js: Authentication Strategies for Express

Learn how Passport.js separates authentication strategies from your routes, how serializeUser and sessions fit in, and run a mini-Passport with local and bearer-token strategies.

Almost every application needs to answer one question for each request: who is this? The answer can come from a username and password, a token in a header, a "Sign in with Google" button, or a signed cookie. Each method has its own rules, but the code around it looks the same: find the credentials, check them, remember the user, and let the request continue or answer 401.

Passport is the library that standardizes that outer shape. It is middleware for Express (and compatible frameworks) that delegates the checking to interchangeable plug-ins called strategies: passport-local for passwords, passport-jwt for bearer tokens, passport-google-oauth20, passport-github2 and hundreds more for social sign-in. Your routes stay the same whichever strategies you use.

Passport itself cannot be installed in our editor, so real code appears read-only, and the runnable examples use a mini-Passport with the same shape: use, authenticate, serializeUser, deserializeUser, req.login, req.user. If you have read Sessions and JWT you already know what is under the hood; here you see the structure Passport puts on top.

The three moving parts

  1. A strategy knows how to find and check credentials. You give it a verify callback that looks the user up. The callback calls done(error, user, info): done(null, user) for success, done(null, false) for "wrong credentials", done(err) for a real failure such as a database outage.
  2. passport.authenticate('name') is route middleware. It runs the strategy and either continues with req.user set or answers 401 (or redirects to a login page).
  3. Session support (optional). With sessions, authenticating once is enough: Passport stores a small piece of the user, usually the id, in the session through serializeUser, and on each later request deserializeUser turns it back into req.user. With tokens you skip sessions entirely ({ session: false }), because every request carries its own proof.

Here is the classic local-strategy setup in real Express code:

JavaScript
import express from 'express';
import session from 'express-session';
import passport from 'passport';
import { Strategy as LocalStrategy } from 'passport-local';

passport.use(new LocalStrategy(async (username, password, done) => {
  try {
    const user = await users.findByName(username);
    if (!user || !(await verifyPassword(password, user.passwordHash))) {
      return done(null, false, { message: 'Wrong username or password' });
    }
    return done(null, user);
  } catch (err) {
    return done(err);
  }
}));

passport.serializeUser((user, done) => done(null, user.id));
passport.deserializeUser(async (id, done) => {
  try { done(null, await users.findById(id)); } catch (err) { done(err); }
});

const app = express();
app.use(express.json());
app.use(session({ secret: process.env.SESSION_SECRET, resave: false, saveUninitialized: false }));
app.use(passport.initialize());
app.use(passport.session());

app.post('/login', passport.authenticate('local'), (req, res) => res.json({ user: req.user.name }));
app.get('/me', (req, res) => (req.isAuthenticated() ? res.json(req.user) : res.sendStatus(401)));
app.post('/logout', (req, res, next) => req.logout((err) => (err ? next(err) : res.sendStatus(204))));

Notice what is not in the strategy: how sessions are stored, how routes are laid out, how passwords are hashed. Passport only wires the pieces together, and each piece can be replaced independently.

A mini-Passport you can run

The code below is a working miniature of the pattern, built from the same four roles. The LocalStrategy reads username and password from the JSON body, the BearerStrategy reads a signed token from the Authorization header, and a tiny cookie session carries the user id for the local strategy. Passwords are hashed with scrypt (see Password Hashing); the token is a real HMAC-signed JWT built with node:crypto.

Node.js Mini-Passport: local strategy with a session, bearer strategy without

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Read the output from top to bottom and map each line to Passport's flow. Before logging in, /me has no req.user. A wrong password makes the verify callback call done(null, false), which the strategy turns into fail, and authenticate answers 401. A correct login calls success, which serializes the id into the session; the next request carries the cookie, session() deserializes the id, and /me sees the user. The bearer routes never touch the session at all (session: false): the token is verified on every request.

The three outcomes of done()

The difference between done(null, false) and done(err) decides what the client sees: a wrong password is the client's problem (401), a database outage is yours (500). This small experiment runs the same verify callback against three situations.

Node.js done(null, user), done(null, false) and done(err)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The third result keeps the internal message in a separate log field and the client body stays generic, which is the rule from Error Handling in Production.

JWT and other strategies

With passport-jwt the strategy is configured with where to find the token and how to verify it, and your callback receives the decoded payload. The real thing (read-only):

JavaScript
import { Strategy as JwtStrategy, ExtractJwt } from 'passport-jwt';

passport.use(new JwtStrategy(
  {
    jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
    secretOrKey: process.env.JWT_SECRET,
    algorithms: ['HS256'],
  },
  async (payload, done) => {
    const user = await users.findById(payload.sub);
    return done(null, user ?? false);
  },
));

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

Always pin algorithms; accepting whatever the token header claims is a classic vulnerability. For choosing between sessions and tokens and for refresh-token handling, see Sessions and JWT.

OAuth: "Sign in with Google"

OAuth strategies (Google, GitHub, Facebook and so on) add a redirect to the provider. Two routes are involved: one that sends the browser to the provider, and a callback route the provider sends the browser back to with a one-time code. The strategy swaps the code for the user's profile and calls your verify callback, where you find or create a local user for that profile.

sequenceDiagram
    participant B as Browser
    participant A as Your app
    participant P as Provider
    B->>A: GET /auth/google
    A-->>B: 302 to the provider with client_id and scope
    B->>P: user signs in and approves
    P-->>B: 302 to /auth/google/callback?code=...
    B->>A: GET /auth/google/callback?code=...
    A->>P: exchange code and client secret for profile
    P-->>A: profile (id, email, name)
    A-->>B: session cookie, 302 to /dashboard

The code travels through the browser, but the secret exchange happens server to server.

JavaScript
import { Strategy as GoogleStrategy } from 'passport-google-oauth20';

passport.use(new GoogleStrategy(
  {
    clientID: process.env.GOOGLE_CLIENT_ID,
    clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    callbackURL: 'https://example.com/auth/google/callback',
  },
  async (accessToken, refreshToken, profile, done) => {
    const user = await users.findOrCreateByProvider('google', profile.id, profile.displayName);
    done(null, user);
  },
));

app.get('/auth/google', passport.authenticate('google', { scope: ['profile', 'email'] }));
app.get('/auth/google/callback',
  passport.authenticate('google', { failureRedirect: '/login' }),
  (req, res) => res.redirect('/dashboard'));

Never trust the provider's profile for authorization decisions beyond identity: map the provider id to your own user record, and use your own roles and permissions.

Habits that keep authentication safe

  • Store only the id in the session (serializeUser), and load the fresh user on each request, so a role change or ban takes effect immediately.
  • Hash passwords with scrypt, argon2 or bcrypt and compare in constant time. Never log credentials.
  • Rate-limit /login; see Rate Limiting and API Protection.
  • Regenerate the session on login (req.session.regenerate) to prevent session fixation, and set HttpOnly, Secure and SameSite on the cookie.
  • Say the same thing for "no such user" and "wrong password". The example's info text is for logs; a public response should not reveal which one failed.
  • Authorize separately. Passport answers "who are you"; whether this user may do something is your code's job.

Passport has a reputation for being old-fashioned, and newer libraries (Auth.js, Lucia-style session helpers, hosted identity providers) offer more complete solutions. It is still worth understanding because the strategy pattern appears everywhere and a very large number of existing Express apps use it.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In a Passport verify callback, which call means 'the credentials were wrong' (not a system failure)?

    done(err) is for real errors such as a database failure. done(null, false) says authentication failed normally, so Passport answers 401 or redirects to the failure page.
  2. 2. What does serializeUser usually store in the session?

    Storing the id keeps the session small and safe; deserializeUser then loads the current user from the database on every request.
  3. 3. Why do bearer-token routes use authenticate('jwt', { session: false })?

    With a token the client proves who it is on each request, so Passport should not create or read a session for that route.
  4. 4. In the OAuth flow, why does the app exchange the code for a profile on the server?

    The one-time code passes through the browser, but exchanging it needs the client secret, which must stay on your server.

Summary

  • Passport separates authentication into strategies (how to check credentials) and middleware (authenticate) that your routes use unchanged.
  • A verify callback ends with done(err), done(null, false) or done(null, user).
  • With sessions, serializeUser stores an id and deserializeUser rebuilds req.user on later requests; with tokens use { session: false }.
  • JWT strategies need pinned algorithms and a secret; OAuth strategies add a redirect and a callback and map provider profiles to your own users.
  • Keep sessions small, hash passwords, rate-limit login, and treat authorization as a separate step.

Next: Validation.