Next.js Security Mistakes AI Assistants Make
Next.js blurs the line between server and client, which is great for productivity and risky when an AI assistant gets the boundary wrong. These are the Next.js-specific mistakes we see most, all rooted in code running somewhere it shouldn't.
Leaking secrets with NEXT_PUBLIC_
Any environment variable prefixed `NEXT_PUBLIC_` is inlined into the client bundle. Assistants sometimes add the prefix to fix an `undefined` value at build time — and in doing so publish a secret to every visitor. Secrets must use an unprefixed var read only in server code. More in Stop Leaking API Keys.
Trusting the client in Server Actions and route handlers
A Server Action runs on the server but is callable by anyone who can reach your site — it's effectively a public endpoint. If it doesn't re-check authentication and authorization on the server, a user can invoke it with any arguments they like. Never rely on the UI hiding a button as your access control.
Auth checks in the wrong place
Putting a redirect only in client components or only in middleware leaves gaps. Middleware is great for coarse gating, but every data-fetching server component and route handler that returns sensitive data must independently verify the session. Defense in depth, not a single checkpoint.
Leaky errors and the `app/api` surface
Returning raw error objects or stack traces from API routes can spill env values, file paths, and query details. Return generic messages to clients and log the detail server-side. Also confirm you're not accidentally serving source maps or debug endpoints in production.
Headers left at defaults
Next.js won't add a CSP or HSTS for you. Configure them in `next.config.js` `headers()` (or your host). Pair this with the rest of the pre-launch checklist before you ship.