Authentication answers who a user is; authorization answers whether that user may access a specific resource or perform an action. A secure Next.js application must check both at the server boundary, even when the UI already hides unavailable controls.
Protect session handling
Use an established authentication library and configure cookies with secure attributes appropriate to the deployment, including
HttpOnlySecureSameSiteCookie-authenticated mutations need CSRF defenses appropriate to the framework and request pattern. Validate origin or anti-CSRF tokens as designed, and do not treat CORS as a CSRF defense. Validate request bodies at runtime and authorize access to the specific record after loading it.
Keep server and client data separate
Server Components and Route Handlers can access privileged resources, but anything serialized to a Client Component is visible to that browser. Return only fields the interface needs. For redirects after login, validate destination URLs to prevent open redirects.
Test anonymous requests, expired sessions, cross-user resource IDs, forged origins, and revoked permissions. Review the framework and auth library’s current security guidance because defaults change. The most important boundary is the server-side check immediately before protected data access or mutation.
Verify the request and the resource
Next.js's Server Actions documentation describes checking Origin against Host or the forwarded host as a framework safeguard. The action still needs application authorization. Load the authenticated actor on the server and check access to the specific draft before selecting or changing it. Apply that rule in the underlying data path as well as the page that shows the editor. Next.js data security guide
Cookie settings express how the browser sends a session credential. Secure restricts transmission to secure contexts subject to documented localhost behavior. HttpOnly keeps script access away from the cookie. SameSite affects cross-site requests, with important differences among its settings. Test the configuration against sign-in redirects and same-site requests, and test whether the mutation rejects a valid session from someone who does not own the draft. HTTP cookie attributes
Worked example
Derive sessionUserId on the server, never from the request body. Call the policy from every underlying read path; hiding an edit button does not secure an API.
tsinterface OwnedArticle { authorId: string; content: string; } function readPrivateArticle(article: OwnedArticle, sessionUserId: string): string { if (article.authorId !== sessionUserId) throw new Error("Article not found"); return article.content; }




Community
Discussion
Loading comments…