Exercise 2: Closing Chapter 8's Gap — Possible Solution ==================================================================== MIDDLEWARE ------------------------------ // middleware/requireAuth.js function requireAuth(req, res, next) { if (!req.session.userId) { return res.status(401).json({ error: 'Not authenticated' }); } next(); } module.exports = requireAuth; UPDATED ENDPOINT ------------------------------ // routes/admin.js const requireAuth = require('../middleware/requireAuth'); const { z } = require('zod'); const titleSchema = z.object({ title: z.string().min(1).max(255), }); app.post('/api/pages/:id/title', requireAuth, async (req, res) => { const result = titleSchema.safeParse(req.body); if (!result.success) { return res.status(400).json({ error: result.error.flatten() }); } await pool.query('UPDATE pages SET title = ? WHERE id = ?', [result.data.title, req.params.id]); res.json({ status: 'ok' }); }); CONFIRMATION ------------------------------ Sending the same request from Chapter 8's own exercises, but with no active session (no logged-in cookie present), now returns a 401 status immediately - requireAuth's own check runs before the route handler itself, since it's registered as middleware ahead of it. Sending the identical request while genuinely logged in succeeds exactly as it did in Chapter 8. WHY THIS WORKS AS AN ANSWER ------------------------------ It correctly builds requireAuth as real Express middleware, correctly applies it ahead of the route handler, and correctly confirms an unauthenticated request is now rejected with 401 before reaching validation or the database.