{"id":14801,"library":"passport","title":"Passport","description":"Passport is an Express-compatible authentication middleware for Node.js. It provides a simple, unobtrusive way to authenticate requests through an extensible set of 'strategies' (plugins) for various authentication methods like username/password, OAuth, or OpenID. It focuses solely on authentication, allowing developers to make application-level decisions about database schemas and routing. The current stable version is 0.7.0, and it is actively maintained.","status":"active","version":"0.7.0","language":"javascript","source_language":"en","source_url":"git://github.com/jaredhanson/passport","tags":["javascript","express","connect","auth","authn","authentication"],"install":[{"cmd":"npm install passport","lang":"bash","label":"npm"},{"cmd":"yarn add passport","lang":"bash","label":"yarn"},{"cmd":"pnpm add passport","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"Also supports CommonJS: const passport = require('passport')","symbol":"passport","correct":"import passport from 'passport'"}],"quickstart":{"code":"import express from 'express';\nimport session from 'express-session';\nimport passport from 'passport';\nimport { Strategy as LocalStrategy } from 'passport-local';\n\nconst app = express();\n\n// Mock User database (in-memory)\nconst users = [{ id: '1', username: 'testuser', password: 'password123' }];\n\n// Configure Passport local strategy\npassport.use(new LocalStrategy(\n  (username, password, done) => {\n    const user = users.find(u => u.username === username);\n    if (!user || user.password !== password) {\n      return done(null, false, { message: 'Incorrect username or password.' });\n    }\n    return done(null, user);\n  }\n));\n\n// Configure Passport session serialization/deserialization\npassport.serializeUser((user, done) => {\n  done(null, user.id);\n});\n\npassport.deserializeUser((id, done) => {\n  const user = users.find(u => u.id === id);\n  done(null, user);\n});\n\n// Setup Express middleware\napp.use(session({\n  secret: process.env.SESSION_SECRET ?? 'a-very-secret-key', // Use a strong secret in production\n  resave: false,\n  saveUninitialized: false\n}));\napp.use(passport.initialize());\napp.use(passport.session());\napp.use(express.urlencoded({ extended: false })); // For form parsing\n\n// Example routes\napp.get('/login', (req, res) => {\n  res.send('<form action=\"/login\" method=\"POST\">Username: <input name=\"username\"/><br/>Password: <input type=\"password\" name=\"password\"/><br/><button type=\"submit\">Login</button></form>');\n});\n\napp.post('/login',\n  passport.authenticate('local', {\n    successRedirect: '/profile',\n    failureRedirect: '/login',\n    failureMessage: true\n  })\n);\n\napp.get('/profile', (req, res) => {\n  if (!req.isAuthenticated()) {\n    return res.redirect('/login');\n  }\n  res.send(`Welcome, ${req.user.username}! This is your profile.`);\n});\n\napp.listen(3000, () => console.log('Server running on port 3000'));\n\n// To run this example:\n// npm install express express-session passport passport-local\n// Add \"type\": \"module\" to your package.json for ESM support.","lang":"javascript","description":"This quickstart demonstrates how to set up Passport with Express and a 'local' authentication strategy. It includes user serialization/deserialization for session management, a mock user database, and basic login/profile routes to show authentication in action. Users can access a protected profile route after logging in."},"warnings":[{"fix":"Install the appropriate `passport-strategy-name` package(s) and register them with `passport.use(new Strategy(...))`.","message":"Passport itself does not include any authentication logic or strategies. You must install and configure specific strategy packages (e.g., `passport-local`, `passport-google-oauth2`) separately for each authentication method you wish to use.","severity":"gotcha","affected_versions":">=0.1.0"},{"fix":"Install `express-session` and ensure `app.use(session(...))`, `app.use(passport.initialize())`, and `app.use(passport.session())` are called in your Express app middleware chain.","message":"For persistent login sessions, Passport requires a session middleware (like `express-session`) to be set up and integrated via `app.use(passport.initialize())` and `app.use(passport.session())`.","severity":"gotcha","affected_versions":">=0.1.0"},{"fix":"Define `passport.serializeUser((user, done) => { done(null, user.id); });` and `passport.deserializeUser((id, done) => { /* fetch user by id */ done(null, user); });`","message":"You must implement `passport.serializeUser` and `passport.deserializeUser` functions for session management to work correctly. Without them, users cannot be stored in or retrieved from the session.","severity":"gotcha","affected_versions":">=0.1.0"},{"fix":"Ensure `passport.use(new MyStrategy({ name: 'my-strategy' }, ...))` is called, and then use `passport.authenticate('my-strategy', ...)`.","message":"The `passport.authenticate()` middleware requires a string argument specifying the name of the strategy to use (e.g., 'local'). This name must correspond to a strategy previously registered with `passport.use()`.","severity":"gotcha","affected_versions":">=0.1.0"},{"fix":"Always call `done()` with the appropriate arguments. `done(null, false)` indicates failed login (e.g., bad credentials), `done(err)` for system errors, and `done(null, user)` for successful authentication.","message":"Strategy callback functions (e.g., `LocalStrategy`'s `verify` function) must call the `done()` callback correctly to indicate success (`done(null, user)`), failure (`done(null, false)`), or an error (`done(err)`). Incorrect calls can lead to authentication issues or unhandled errors.","severity":"gotcha","affected_versions":">=0.1.0"}],"env_vars":null,"last_verified":"2026-04-18T00:00:00.000Z","next_check":"2026-07-17T00:00:00.000Z","problems":[{"fix":"Add `app.use(passport.initialize());` before any routes or other Passport middleware.","cause":"The `passport.initialize()` middleware was not added to the Express application.","error":"Error: Passport is not initialized. To use Passport middleware, you must first call passport.initialize()."},{"fix":"Implement `passport.serializeUser((user, done) => { done(null, user.id); });` (replace `user.id` with a unique identifier for your user).","cause":"The `passport.serializeUser` function was not defined or returned an invalid value.","error":"Error: Failed to serialize user into session"},{"fix":"Implement `passport.deserializeUser((id, done) => { /* find user by id from your database */ done(null, user); });`","cause":"The `passport.deserializeUser` function was not defined or failed to retrieve a user for the provided ID.","error":"Error: Failed to deserialize user from session"},{"fix":"Ensure `passport.use(new LocalStrategy(...))` (or the equivalent for your chosen strategy) is called after importing the strategy and before `passport.authenticate()` is used.","cause":"The 'local' strategy (or any specified strategy) has not been registered with Passport using `passport.use()`.","error":"Error: Unknown authentication strategy \"local\""},{"fix":"Ensure the user is properly authenticated, `passport.deserializeUser` is correctly implemented and fetching a user, and check `req.isAuthenticated()` before accessing `req.user`.","cause":"Attempting to access `req.user` when no user is authenticated or `deserializeUser` failed to populate `req.user`.","error":"TypeError: Cannot read properties of undefined (reading 'username')"}],"ecosystem":"npm"}