Registry / auth-security / passport

passport

JSON →
library0.1.1jsnpmunverified

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.

npm install passport
INSTALL
IMPORT
SIG · PASSPORT
P
passport
auth-securityjavascriptv0.1.1
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

passport
import passport from 'passport'
Also supports CommonJS: const passport = require('passport')

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.

import express from 'express'; import session from 'express-session'; import passport from 'passport'; import { Strategy as LocalStrategy } from 'passport-local'; const app = express(); // Mock User database (in-memory) const users = [{ id: '1', username: 'testuser', password: 'password123' }]; // Configure Passport local strategy passport.use(new LocalStrategy( (username, password, done) => { const user = users.find(u => u.username === username); if (!user || user.password !== password) { return done(null, false, { message: 'Incorrect username or password.' }); } return done(null, user); } )); // Configure Passport session serialization/deserialization passport.serializeUser((user, done) => { done(null, user.id); }); passport.deserializeUser((id, done) => { const user = users.find(u => u.id === id); done(null, user); }); // Setup Express middleware app.use(session({ secret: process.env.SESSION_SECRET ?? 'a-very-secret-key', // Use a strong secret in production resave: false, saveUninitialized: false })); app.use(passport.initialize()); app.use(passport.session()); app.use(express.urlencoded({ extended: false })); // For form parsing // Example routes app.get('/login', (req, res) => { 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>'); }); app.post('/login', passport.authenticate('local', { successRedirect: '/profile', failureRedirect: '/login', failureMessage: true }) ); app.get('/profile', (req, res) => { if (!req.isAuthenticated()) { return res.redirect('/login'); } res.send(`Welcome, ${req.user.username}! This is your profile.`); }); app.listen(3000, () => console.log('Server running on port 3000')); // To run this example: // npm install express express-session passport passport-local // Add "type": "module" to your package.json for ESM support.
Debug
Known issues
gotchaPassport 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.
fix
Install the appropriate `passport-strategy-name` package(s) and register them with `passport.use(new Strategy(...))`.
affects: >=0.1.0
gotchaFor 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())`.
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.
affects: >=0.1.0
gotchaYou 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.
fix
Define `passport.serializeUser((user, done) => { done(null, user.id); });` and `passport.deserializeUser((id, done) => { /* fetch user by id */ done(null, user); });`
affects: >=0.1.0
gotchaThe `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()`.
fix
Ensure `passport.use(new MyStrategy({ name: 'my-strategy' }, ...))` is called, and then use `passport.authenticate('my-strategy', ...)`.
affects: >=0.1.0
gotchaStrategy 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.
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.
affects: >=0.1.0
Errors
Common errors & fixes
Error: Passport is not initialized. To use Passport middleware, you must first call passport.initialize().
The `passport.initialize()` middleware was not added to the Express application.
fix
Add `app.use(passport.initialize());` before any routes or other Passport middleware.
Error: Failed to serialize user into session
The `passport.serializeUser` function was not defined or returned an invalid value.
fix
Implement `passport.serializeUser((user, done) => { done(null, user.id); });` (replace `user.id` with a unique identifier for your user).
Error: Failed to deserialize user from session
The `passport.deserializeUser` function was not defined or failed to retrieve a user for the provided ID.
fix
Implement `passport.deserializeUser((id, done) => { /* find user by id from your database */ done(null, user); });`
Error: Unknown authentication strategy "local"
The 'local' strategy (or any specified strategy) has not been registered with Passport using `passport.use()`.
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.
TypeError: Cannot read properties of undefined (reading 'username')
Attempting to access `req.user` when no user is authenticated or `deserializeUser` failed to populate `req.user`.
fix
Ensure the user is properly authenticated, `passport.deserializeUser` is correctly implemented and fetching a user, and check `req.isAuthenticated()` before accessing `req.user`.
Upgrade
Version history
0.1.1latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
10 hits · last 30 days
node
8
Amazon
1
OpenAI (training)
1
Resources