Passport.js — Authentication Middleware Guide
Advertisement
Passport.js is the most popular authentication middleware for Node.js. Supports 500+ strategies out of the box.
Local Strategy
npm install passport passport-local express-session bcryptjs
import passport from "passport";
import LocalStrategy from "passport-local";
import bcrypt from "bcryptjs";
passport.use(
new LocalStrategy(
{
usernameField: "email",
passwordField: "password",
},
async (email, password, done) => {
try {
const user = await db.users.findOne({ email });
if (!user) return done(null, false, { message: "User not found" });
const valid = await bcrypt.compare(password, user.password);
if (!valid) return done(null, false, { message: "Invalid password" });
return done(null, user);
} catch (error) {
return done(error);
}
}
)
);
passport.serializeUser((user: any, done) => done(null, user.id));
passport.deserializeUser(async (id, done) => {
const user = await db.users.findById(id);
done(null, user);
});
Routes
app.post(
"/login",
passport.authenticate("local", { failureRedirect: "/login" }),
(req, res) => {
res.redirect("/dashboard");
}
);
app.get("/logout", (req, res) => {
req.logout(() => res.redirect("/"));
});
app.get("/profile", (req: any, res) => {
if (!req.isAuthenticated()) return res.status(401).json({ error: "Not auth" });
res.json(req.user);
});
Custom Middleware
const ensureAuthenticated = (req: any, res: any, next: any) => {
if (req.isAuthenticated()) return next();
res.status(401).json({ error: "Not authenticated" });
};
const ensureAdmin = (req: any, res: any, next: any) => {
if (req.isAuthenticated() && req.user.role === "admin") return next();
res.status(403).json({ error: "Forbidden" });
};
app.get("/admin", ensureAdmin, (req, res) => {
res.json({ admin: true });
});
FAQ
Q: What's the best strategy? A: JWT for APIs, sessions for web apps, OAuth for social login.
Q: Can I combine strategies? A: Yes, use multiple strategies and let users choose.
Q: How do I handle CSRF? A: Use csurf middleware alongside Passport.
Passport.js remains the gold standard for Node.js authentication.
Advertisement