Production engineering workshop · 45 MIN
Next.js · Authorize every server-side mutation
A hidden button is not an authorization boundary.
Treat a Route Handler as a public API. Verify the authenticated identity, validate request shape, enforce a same-origin policy for cookie-authenticated writes, and scope the database operation by owner. Server Components can read private data only after the same ownership checks. The dependency functions in this example are application-specific; implement them using your session and database layer. This lesson targets Next.js 15 route semantics.
First reproduce the normal path. Then force a failure at each boundary and inspect what remains true.
Read the example
// app/api/notes/[id]/route.ts
import {z} from "zod";
import {requireUser,updateOwnedNote} from "@/server/notes";
const input=z.object({text:z.string().trim().min(1).max(4000)}).strict();
export async function PUT(request:Request, context:{params:Promise<{id:string}>}) {
if (request.headers.get("origin") !== process.env.APP_ORIGIN)
return Response.json({error:"Forbidden"},{status:403});
const user=await requireUser(request);
if (!user) return Response.json({error:"Sign in"},{status:401});
// Production dependency must stream-limit the body before JSON parsing.
const data=input.safeParse(await request.json().catch(()=>null));
if (!data.success) return Response.json({error:"Invalid note"},{status:400});
const {id}=await context.params;
const updated=await updateOwnedNote({id,ownerId:user.id,text:data.data.text});
return updated ? Response.json({ok:true},{headers:{"Cache-Control":"no-store"}})
: Response.json({error:"Not found"},{status:404});
}
// updateOwnedNote must use a parameterized predicate:
// UPDATE notes SET text=? WHERE id=? AND owner_id=?Check the expected output
Review the behavior in the stated project environment.
Your challenge
Create app/api/notes/[id]/route.ts. Implement requireUser and updateOwnedNote as server-only dependencies. Return the same 404 for missing and foreign notes. Test absent session, foreign owner, invalid JSON, wrong Origin and a successful update.
Solution cost: Indexed update O(log n) in a typical B-tree; validate with the actual database. time · Bounded request body and one updated record. space
Common trap
Trusting ownerId supplied by the browser lets a caller choose whose data to modify.
Study the project implementation
// app/api/notes/[id]/route.ts
import {z} from "zod";
import {requireUser,updateOwnedNote} from "@/server/notes";
const input=z.object({text:z.string().trim().min(1).max(4000)}).strict();
export async function PUT(request:Request, context:{params:Promise<{id:string}>}) {
if (request.headers.get("origin") !== process.env.APP_ORIGIN)
return Response.json({error:"Forbidden"},{status:403});
const user=await requireUser(request);
if (!user) return Response.json({error:"Sign in"},{status:401});
// Production dependency must stream-limit the body before JSON parsing.
const data=input.safeParse(await request.json().catch(()=>null));
if (!data.success) return Response.json({error:"Invalid note"},{status:400});
const {id}=await context.params;
const updated=await updateOwnedNote({id,ownerId:user.id,text:data.data.text});
return updated ? Response.json({ok:true},{headers:{"Cache-Control":"no-store"}})
: Response.json({error:"Not found"},{status:404});
}
// updateOwnedNote must use a parameterized predicate:
// UPDATE notes SET text=? WHERE id=? AND owner_id=?Further reading: Official documentation