Node.js Lesson 14: JWT Authentication
Authentication verifies WHO is making a request. JWT (JSON Web Token) is the standard for stateless authentication in REST APIs.
How JWT Works
// 1. User logs in with email + password
// 2. Server verifies password, creates a JWT
// 3. Server sends JWT to client
// 4. Client stores JWT (localStorage or httpOnly cookie)
// 5. Client sends JWT in every future request
// 6. Server verifies JWT, identifies user
// JWT structure: header.payload.signature
// eyJhbGciOiJIUzI1NiJ9.eyJ1c2VySWQiOjF9.XxXx...
Login & Token Generation
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
// npm install bcrypt jsonwebtoken
// Register: hash password
app.post("/auth/register", async (req, res) => {
const { email, password, name } = req.body;
const hashedPassword = await bcrypt.hash(password, 10);
const user = await User.create({ name, email, password: hashedPassword });
res.status(201).json({ id: user._id, name, email });
});
// Login: verify password, return token
app.post("/auth/login", async (req, res) => {
const { email, password } = req.body;
const user = await User.findOne({ email });
if (!user) return res.status(401).json({ error: "Invalid credentials" });
const valid = await bcrypt.compare(password, user.password);
if (!valid) return res.status(401).json({ error: "Invalid credentials" });
const token = jwt.sign({ userId: user._id }, process.env.JWT_SECRET, { expiresIn: "7d" });
res.json({ token, user: { id: user._id, name: user.name, email } });
});
Auth Middleware
function authenticate(req, res, next) {
const authHeader = req.headers.authorization;
if (!authHeader?.startsWith("Bearer ")) {
return res.status(401).json({ error: "No token" });
}
const token = authHeader.split(" ")[1];
try {
const payload = jwt.verify(token, process.env.JWT_SECRET);
req.userId = payload.userId; // available in route handlers
next();
} catch {
res.status(401).json({ error: "Invalid or expired token" });
}
}
// Protect routes
app.get("/api/profile", authenticate, async (req, res) => {
const user = await User.findById(req.userId).select("-password");
res.json(user);
});
🏋️ Practice Task
Add JWT auth to your API. Create /auth/register and /auth/login routes. Create an authenticate middleware. Protect /api/profile (returns logged-in user) and /api/users/:id/delete (can only delete own account).
💡 Hint: Test with Postman: POST /auth/login → copy token → GET /api/profile with header: Authorization: Bearer