IHOR.DEVKNOWLEDGE_BASE
MENU

~/blog / Web Stack / authentication-architecture-in-next-js.md

// guide · 4 min read

Authentication Architecture in Next.js

Place Next.js authentication, session verification, record authorization, and public projections in a server data layer while keeping proxy redirects as navigation aids.

Quick answer

Authenticate the user through a maintained auth integration, verify the session on the server, and authorize each protected record read and mutation near the data. A proxy redirect or protected layout can improve navigation but cannot replace those checks. Separate identity from permission: a valid session proves a recognized user, not entitlement to every account, tenant, or administrative operation.

Practical implementation steps

1. Centralize verified session access

Use one server-only session reader instead of separately parsing cookies in pages, actions, and Route Handlers. Let the integration handle protocol and cryptographic details. Decide expiration, logout, and revocation behavior explicitly. Do not trust an email address, role, or user ID simply because it came from a browser form or an unverified token payload.

2. Enforce record scope before projection

A report lookup should combine its identifier with the authorized owner or tenant scope. Check role-based exceptions deliberately rather than using a global isLoggedIn condition. Return only fields needed by the view. Even a Server Component can leak information through HTML, serialized props, error messages, or metadata, so keeping the database call on the server is only part of the boundary.

3. Protect every callable mutation

A hidden button does not prevent a direct Server Action or API call. Reverify the session and permission when the operation executes, validate its inputs, and follow the integration’s request-origin and CSRF protections. Keep safe return URLs within the intended application origin. After logout or role changes, check whether cached data or an open browser view still exposes protected information.

Implementation example

This policy function assumes user came from verified server session state and report came from a scoped server read. It does not verify tokens, receive arbitrary client identity, or substitute for query filtering. In a multi-tenant product, add verified tenant membership and scope the lookup by tenant as well. Keep the policy in the authorized data operation so every entrypoint uses it.

type VerifiedUser = { id: string; role: "member" | "admin" };
type Report = { id: string; ownerId: string };

export function canReadReport(
  user: VerifiedUser | null, report: Report,
): boolean {
  if (!user) return false;
  return user.role === "admin" || report.ownerId === user.id;
}

This repository uses NextAuth with GitHub sign-in and an allowlisted GitHub login in its sign-in callback. Its session strategy is JWT. These observed implementation facts describe the portfolio’s restricted admin surface; they do not establish a general enterprise role system or prove that live OAuth has been tested during this editorial review.

Tradeoffs and alternatives

A managed identity provider transfers protocol maintenance but leaves application authorization with the product. Database sessions can make server-side revocation direct; signed stateless sessions need an explicit policy for revocation and role freshness. Decide from operational needs rather than assuming JWT eliminates state or cookies eliminate risk. This article addresses placement of checks; a session-format comparison is a separate decision.

Common mistakes

The main failures are checking only in a layout, accepting role claims from the client, reading by record ID before applying scope, and sharing protected output under a public cache key. Another is returning whole database records as client props. Error responses and logging also need deliberate projections; raw records and tokens are not useful debugging output to expose to visitors.

Production checklist

  • All protected entrypoints use verified session state.
  • Record and tenant permissions constrain the data read.
  • Mutations recheck permission and validate inputs.
  • Client output excludes private fields and credentials.
  • Logout, expiry, and role change have explicit behavior.

FAQ

Is a proxy enough to protect the application?

No. Use it for early routing decisions where appropriate, then enforce the definitive access check at the protected operation. Do not depend on every caller passing through one UI route.

Can public and private pages share a layout?

Yes, but keep public output independently safe to cache and put private reads behind verified authorization. Avoid making session-dependent behavior an accidental property of every public route.

Next step

Inventory pages, handlers, and actions that read or change protected data. Trace each to the same session and authorization layer, then check expired sessions, denied records, and changed roles. Add navigation redirects after that access model is correct.

Primary sources

Ihor Kharchyshyn

Independent full-stack product engineer writing source-backed implementation guides for browser extensions and modern web products.

Need this implemented in a real product?

React and Next.js applications with deliberate rendering, reliable data flows, and a clear path to production.