How to use Passport.js in Node.js
Passport.js provides a comprehensive authentication middleware for Node.js applications with support for over 500 authentication strategies. As the creator of CoreUI with extensive Node.js experience since 2014, I’ve implemented Passport.js in numerous production applications for flexible authentication solutions. The most straightforward approach uses the local strategy for username/password authentication combined with session management. This pattern provides robust authentication while maintaining the flexibility to add additional strategies like OAuth, SAML, or custom authentication methods.
Configure Passport.js with a local strategy and session management for secure user authentication.
const passport = require('passport')
const LocalStrategy = require('passport-local').Strategy
const bcrypt = require('bcrypt')
const session = require('express-session')
// Configure session middleware
app.use(session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false,
cookie: { secure: false, maxAge: 24 * 60 * 60 * 1000 }
}))
app.use(passport.initialize())
app.use(passport.session())
// Configure local strategy
passport.use(new LocalStrategy(
async (username, password, done) => {
try {
const user = await User.findOne({ username })
if (!user) return done(null, false)
const isValid = await bcrypt.compare(password, user.password)
if (isValid) return done(null, user)
else return done(null, false)
} catch (error) {
return done(error)
}
}
))
// Serialize user for session
passport.serializeUser((user, done) => {
done(null, user.id)
})
passport.deserializeUser(async (id, done) => {
try {
const user = await User.findById(id)
done(null, user)
} catch (error) {
done(error)
}
})
// Login route
app.post('/login', passport.authenticate('local', {
successRedirect: '/dashboard',
failureRedirect: '/login'
}))
This code configures Passport.js with a local strategy that validates username/password combinations against a user database. The serialize/deserialize functions manage user sessions, storing only the user ID in the session and retrieving the full user object when needed. The middleware automatically handles authentication flow and redirects based on success or failure.
Best Practice Note:
This is the authentication setup we use in CoreUI Node.js backend services for flexible, secure user authentication. Passport.js supports hundreds of strategies including OAuth providers, making it easy to add social login while maintaining consistent authentication logic.



