lessons/nextjs.md

Lesson 8 of 18

Next.js: the server is the trust boundary

Many things in a Next.js app look like UI but are server endpoints. Treat each one as a public API.

Remember: Every Server Action and Route Handler is an endpoint. Authenticate, authorise the object, and select explicit fields in each one.
  • Server Actions: every exported "use server" function is a public HTTP endpoint. Anyone can call it with any arguments, including ones the UI never sends.
  • Route Handlers: app/api/**/route.ts files are endpoints. Check identity and object ownership inside each handler.
  • Middleware (proxy): good for optimistic redirects. It is not the only barrier, and it has been bypassed before (CVE-2025-29927). Re-check in the handler or the data-access layer.
  • Props passed to Client Components are serialised into the page. Passing a full database row leaks passwordHash and every other field, whatever the TypeScript types say.
  • NEXT_PUBLIC_ variables are compiled into the browser bundle. Never put a secret there.
const user = await db.user.findUnique({ where: { id: session.userId } });
return <ProfileCard user={user} />;
Vulnerable: the whole row is serialised and sent to the browser.
const user = await db.user.findUnique({
where: { id: session.userId },
select: { name: true, avatarUrl: true },
});
Fixed: select only what the UI needs.

A data-access layer

Put database access in one server-only module (import "server-only") that receives a verified userId and returns DTOs. Route handlers and actions then stay thin, and the authorisation rule lives in one place.

In December 2025, React Server Components had an unauthenticated remote code execution bug (CVE-2025-55182, CVSS 10) affecting the App Router. Track framework advisories and patch with a deadline.

Questions to ask yourself

  1. Is this function exported as a Server Action or a Route Handler?
  2. Does the middleware check validity, or only presence?
  3. What exactly is serialised into the page?

Practise this