🚀 Express.js Intermediate

What is Passport.js and how does it integrate with Express?

Answer

Passport.js is authentication middleware for Express that supports 500+ authentication strategies through a unified API. Common strategies: Local (username/password), JWT, OAuth2 (Google, GitHub, Facebook login). Initialize: app.use(passport.initialize());. Define a strategy: passport.use(new LocalStrategy(async (username, password, done) => { const user = await User.findOne({ username }); if (!user || !user.validPassword(password)) return done(null, false); return done(null, user); }));. Protect routes: app.get('/profile', passport.authenticate('jwt', { session: false }), handler);. Passport is flexible and well-documented, making it easy to add social logins or swap authentication mechanisms without changing route code.