image de chargement
Back to glossary

Passport.js

Flexible authentication middleware for Node.js supporting 500+ strategies (OAuth, JWT, local) to secure your web applications.

Updated on January 12, 2026

Passport.js is the most popular authentication middleware for Node.js, offering a modular architecture based on interchangeable strategies. Used by thousands of production applications, it simplifies authentication implementation without imposing rigid structure. Passport.js handles both local authentication (username/password) and OAuth logins (Google, Facebook), JWT, SAML, or any custom mechanism.

Fundamentals

  • Pluggable strategy-based architecture allowing authentication mechanisms to be added or modified without major refactoring
  • Express/Connect middleware integrating naturally into HTTP request flow with session serialization/deserialization
  • Ecosystem of 500+ official and community strategies covering OAuth 1.0/2.0, OpenID, SAML, JWT, and proprietary protocols
  • Clear separation between authentication logic (credential verification) and session management (user persistence)

Benefits

  • Drastic reduction of boilerplate code for implementing multi-provider authentication with a unified API
  • Complete flexibility to combine multiple strategies simultaneously (social login + local authentication + API tokens)
  • Native compatibility with Express.js and integration possible with any Node.js framework accepting Connect middleware
  • Enhanced security through community-maintained and regularly audited strategies
  • Automatic session management with support for multiple stores (Redis, MongoDB, PostgreSQL) via express-session

Practical Example

auth.config.ts
import passport from 'passport';
import { Strategy as LocalStrategy } from 'passport-local';
import { Strategy as JwtStrategy, ExtractJwt } from 'passport-jwt';
import bcrypt from 'bcrypt';
import { UserModel } from './models/User';

// Local strategy (username/password)
passport.use(new LocalStrategy(
  async (username, password, done) => {
    try {
      const user = await UserModel.findOne({ username });
      if (!user) {
        return done(null, false, { message: 'User not found' });
      }
      
      const isValid = await bcrypt.compare(password, user.passwordHash);
      if (!isValid) {
        return done(null, false, { message: 'Incorrect password' });
      }
      
      return done(null, user);
    } catch (error) {
      return done(error);
    }
  }
));

// JWT strategy for API
passport.use(new JwtStrategy(
  {
    jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
    secretOrKey: process.env.JWT_SECRET,
  },
  async (payload, done) => {
    try {
      const user = await UserModel.findById(payload.sub);
      return done(null, user || false);
    } catch (error) {
      return done(error, false);
    }
  }
));

// Session serialization
passport.serializeUser((user: any, done) => {
  done(null, user.id);
});

passport.deserializeUser(async (id: string, done) => {
  try {
    const user = await UserModel.findById(id);
    done(null, user);
  } catch (error) {
    done(error);
  }
});

This configuration demonstrates simultaneous use of two strategies: local authentication for login forms and JWT for API calls. The serialize/deserialize functions manage user persistence in sessions.

Implementation

  1. Install Passport.js and required strategies: `npm install passport passport-local passport-jwt express-session`
  2. Configure authentication strategies by defining credential verification functions for each method
  3. Implement serialize/deserializeUser to manage user session persistence with an appropriate store (Redis recommended in production)
  4. Initialize Passport in Express with `app.use(passport.initialize())` and `app.use(passport.session())` after express-session
  5. Protect routes with `passport.authenticate('strategy-name')` as middleware, specifying redirect or callback options
  6. Configure login/logout routes with error handling and flash messages for user experience
  7. Test authentication flows with success/failure scenarios and validate session/token management

Production Advice

Always use multiple security layers: combine Passport.js with request limiters (express-rate-limit), CSRF protection, helmet.js for secure HTTP headers, and implement JWT token rotation with refresh tokens. Store sessions in Redis rather than in-memory to enable horizontal scalability and avoid session loss during restarts.

  • express-session: server-side session management with support for multiple stores (Redis, MongoDB, PostgreSQL)
  • bcrypt / argon2: secure password hashing with protection against brute-force attacks
  • jsonwebtoken: JWT creation and validation for stateless API authentication
  • passport-google-oauth20 / passport-facebook: OAuth 2.0 strategies for social authentication
  • connect-flash: flash messages for displaying authentication errors in forms
  • helmet: HTTP header security to prevent common vulnerabilities (XSS, clickjacking)

Passport.js represents a strategic investment for any Node.js project requiring robust and scalable authentication. Its flexibility allows starting with simple authentication and progressively evolving toward complex multi-provider architectures without major rewrites. In production, Passport.js significantly reduces security risks by relying on proven and actively maintained strategies, while offering the freedom to adapt authentication to specific business needs.

Related terms

Themoneyisalreadyonthetable.

In 1 hour, discover exactly how much you're losing and how to recover it.