Node.js › Authentication & Authorization

What is Passport.js, and how do its 'strategies' provide a consistent authentication abstraction across different methods?

Intermediate

Answer

Passport.js is a widely used Express-compatible authentication middleware built around the concept of 'strategies' -- pluggable modules each implementing one specific authentication method (local username/password, Google OAuth, JWT, SAML, and hundreds of others) behind a consistent interface, so an application can support multiple authentication methods side by side, or switch between them, with minimal changes to route-handling code.
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;

passport.use(new LocalStrategy(async (username, password, done) => {
  const user = await User.findOne({ username });
  if (!user || !(await user.comparePassword(password))) return done(null, false);
  return done(null, user);
}));

app.post('/login', passport.authenticate('local'), (req, res) => res.json({ success: true }));
Real-world example An application supporting both traditional username/password login and 'Sign in with GitHub' registers both a LocalStrategy and a GitHubStrategy with Passport, letting both authentication paths converge on the same req.user object and the same downstream authorization logic.

Common follow-ups: How does Passport's session serialization (serializeUser/deserializeUser) work to keep the session payload small?;What's a scenario where implementing authentication manually might be preferable to depending on Passport?