← Lesson
BitWithBite
Full-Stack · Quick Reference

Lesson 27 — JWT Authentication Cheat Sheet

Full-Stack
In one line: Hash passwords with bcrypt, issue a signed JWT at login, and verify it with middleware before protected routes run.

Key Ideas

1bcrypt.hash(). One-way hashes a password.
2bcrypt.compare(). Verifies a password against its hash.
3jwt.sign(). Creates a signed token with an expiry.
4jwt.verify(). Validates a token's signature.
5JWT_SECRET. Must live in env vars, never in code.

Protect Middleware

function protect(req,res,next) { const token = req.headers.authorization?.split(' ')[1]; if (!token) return res.status(401).json({error:'No token'}); try { req.user = jwt.verify(token, process.env.JWT_SECRET); next(); } catch { res.status(401).json({error:'Invalid'}); } }