Exercise 2: Closing Chapter 8's Gap — Possible Solution ==================================================================== UPDATED ENDPOINT ------------------------------ // src/pages/api/pages/[id]/title.ts import { getSession } from 'auth-astro/server'; import { z } from 'zod'; const titleSchema = z.object({ title: z.string().min(1).max(255), }); export const POST: APIRoute = async ({ params, request }) => { const session = await getSession(request); if (!session) { return new Response(null, { status: 401 }); } const body = await request.json(); const result = titleSchema.safeParse(body); if (!result.success) { return new Response(JSON.stringify({ error: result.error.flatten() }), { status: 400 }); } await db.update(pages).set({ title: result.data.title }).where(eq(pages.id, Number(params.id))); return new Response(JSON.stringify({ 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, before the Zod validation or the database update ever run. Sending the identical request while genuinely logged in succeeds exactly as it did in Chapter 8. WHY THIS WORKS AS AN ANSWER ------------------------------ It correctly adds the getSession() check as the very first thing the endpoint does, and correctly confirms an unauthenticated request is now rejected with 401 rather than reaching validation or the database at all.