Express.js Masterclass
The Professional Backend Framework01.Home02.Introduction03.Express vs Native Node04.Express Generator05.Request Object (req)06.Response Object (res)07.Advanced Routing08.URL Params & Query09.Body Parsing10.Template Engines (EJS)11.Serving Static Files12.Middleware Architecture13.Must-Have Middleware14.File Uploads (Multer)15.Custom Error Handling16.Cookies & Sessions17.User Auth (Passport)18.Database Integration19.Data Validation20.Socket.io in Express21.Security & Helmet
User Authentication (Passport.js)
Passport is an authentication middleware for Node.js. It's extremely flexible and modular, allowing you to plug in different "strategies" like Local, Google, GitHub, etc.
1. Installation
npm install passport passport-local2. Conceptual Workflow
- Initialize Passport in your app.
- Define a Strategy (e.g., how to verify a username and password).
- Configure Serialization (saving user info to session).
- Use
passport.authenticate()in your routes.
3. Local Strategy Example
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
passport.use(new LocalStrategy(
function(username, password, done) {
User.findOne({ username: username }, function (err, user) {
if (err) { return done(err); }
if (!user) { return done(null, false); }
if (!user.verifyPassword(password)) { return done(null, false); }
return done(null, user);
});
}
));4. Protecting Routes
Create a simple helper to check if the user is authenticated.
function checkAuth(req, res, next) {
if (req.isAuthenticated()) return next();
res.redirect('/login');
}
app.get('/dashboard', checkAuth, (req, res) => {
res.render('dashboard', { user: req.user });
});Choosing Auth: Use Sessions/Passport for traditional web apps and JWT for stateless APIs.