Next.js Authentication and Sessions


Authentication answers “who made this request?” Authorization answers “may that actor do this action to this resource now?” A Next.js application needs both answers on the server. A page that hides a button for anonymous users is a good interface; it is not an access-control decision.
Sessions turn an authenticated event into a durable request identity. Treat them as a security boundary with a lifecycle: creation, rotation, verification, expiry, renewal, logout, and revocation. The implementation can use a library or an identity provider, but those responsibilities remain your application’s design work.
Authentication and Authorization Are Different Questions
After a sign-in flow has verified credentials or an identity-provider assertion, the application can establish a session for an actor. That does not grant blanket access. A user may be authenticated and still not belong to a tenant, own a document, approve a payment, or administer a workspace.
export async function requireProjectEditor(projectId: string) {
const session = await requireSession();
const project = await projects.find(projectId);
await policy.assertAllowed({
subject: session.userId,
action: "project:edit",
resource: project,
});
return { session, project };
}The resource is loaded before the policy decision. Never accept a user or tenant identifier from a hidden field and treat it as authorization. The server’s session establishes identity; authoritative resource data establishes the relationship.
Session boundary explorer
Interactive guide: select a lifecycle point to inspect its server-side responsibility.
Sign in
Verify credentials with the identity provider, rotate the session identifier, and set a secure cookie with the narrowest practical scope.
Make the Session a Server-Owned Boundary
For browser applications, a secure, HttpOnly cookie keeps the session credential out of ordinary client-side JavaScript. Set Secure in HTTPS environments, choose an appropriate SameSite policy, constrain Path and Domain where practical, and keep cookie values small. Whether the cookie contains an opaque session identifier or a signed token, validate its expiry, issuer/audience where relevant, signature or server-side record, and revocation state on the server.
Do not put durable authorization decisions in a client store and hope they remain current. A React context can display the known user for convenience, but server components, Route Handlers, Server Actions, and data services must establish the current request identity independently.
Do Not Treat Middleware as the Only Guard
Middleware can improve navigation and redirect behaviour, but it is not a substitute for authorization in the action, route, or data service that performs a consequential operation. Defend the resource boundary itself.
Authorize the Resource on Every Consequential Request
Create small server helpers that establish a session and authorize a named capability against the resource. They reduce repeated logic without turning policy into a vague global role check. A document download, Server Action mutation, Route Handler, background job, and webhook follow different caller paths; each must have a credible actor or service identity and a resource-level decision.
For multi-tenant systems, include tenant membership and resource ownership in every lookup or policy input. Cross-tenant bugs are often not exotic cryptographic failures—they are a query that loaded by ID without checking the tenant relationship.
Expected denials should be controlled: redirect unauthenticated browser users to sign-in, return 403 for an authenticated but unauthorized API caller, and avoid revealing whether a sensitive resource exists. Log a safe actor reference, capability, resource reference, outcome, and correlation ID for security review.
Design Login, Redirect, and Logout Flows Deliberately
Rotate the session identifier after sign-in or privilege elevation to reduce session-fixation risk. Preserve an intended post-login destination only after validating it is a same-origin, allowed path; an unvalidated returnTo parameter becomes an open redirect. Use a short session lifetime appropriate to the risk, renew carefully, and require fresh authentication for particularly sensitive actions.
Logout should clear the browser cookie and invalidate server-side session or refresh-token state where the architecture supports it. A user expects “sign out everywhere” and administrator revocation to stop future requests, not merely hide the account menu. Long-running work should re-check authority when it resumes rather than carrying a stale user session forever.
Opaque sessions and signed tokens have different trade-offs
An opaque session ID points to server-side state. It makes revocation, device management, and changing user permissions straightforward because the server can consult current state on each request. It introduces a session store and its availability/latency considerations. A signed token can reduce that lookup, but it moves claims and expiry into a credential that remains valid until it expires unless a separate revocation strategy is added.
Neither choice removes authorization. A token claim that says a user was an editor when it was issued does not necessarily reflect their membership after an administrator removes it. For sensitive or rapidly changing permissions, consult current server-side policy at the resource boundary. Choose the session representation around revocation, scale, and risk—not because one format is fashionable.
Keep data access behind the same guard
It is easy to protect a page component and forget a server-side loader, cached function, export route, or background action that reads the same data. Centralize access through a service that accepts the established actor and validates tenant/resource policy. The page, Route Handler, and Server Action can each call that service after establishing their caller identity.
This design also prevents accidental cache leaks. Do not cache a result across users if it includes session-specific or authorization-specific data. Make user/tenant variation explicit in the data boundary and verify it under more than one account in integration tests.
Test Revocation and Failure Paths
Test more than the happy login. Verify an anonymous request cannot reach protected data; an authenticated user cannot load another tenant’s record by changing an ID; a session revoked after page render fails the later action; sign-out prevents reuse; expired sessions redirect or return the expected response; and redirect targets cannot leave the application.
Exercise cookie attributes and CSRF-relevant flows in a real browser environment. For cookie-authenticated cross-site requests, choose defenses appropriate to the application—same-site cookie policy, origin checks, anti-CSRF tokens, or an architecture that avoids ambient browser credentials for the endpoint. Do not add a token ritual without understanding which request path it protects.
An implementation review checklist
Before shipping a protected feature, answer these questions in code and tests: Where is the request identity verified? Which exact resource is loaded before authorization? What happens if the session expires after render but before submit? Which cookie attributes and CSRF controls protect the browser path? How does logout invalidate future use? Which cache or data loader could accidentally cross an actor boundary? A clear answer turns security review from “we added auth” into a concrete, maintainable request contract.
Key Takeaways
- Authentication establishes a request identity; authorization decides whether that identity may act on a specific resource.
- Keep session verification on the server and keep browser session cookies inaccessible to ordinary client JavaScript.
- Authorize the authoritative resource at every consequential Route Handler, Server Action, and data boundary.
- Design session rotation, redirect validation, expiry, logout, and revocation as explicit lifecycle events.
- Test cross-tenant access, stale sessions, open redirects, and sign-out/revocation—not only successful login.
Make security incidents repairable
Prepare an operational path before an incident: identify the session record or token family to revoke, the audit events needed to scope access, and the user communication path for a forced sign-out. Practice this with a non-production account. Authentication is not finished at login; its real value is retaining control when identity, device, membership, or risk changes after the request has already begun.
Next, we pause the tutorial sequence for December’s AI engineering trends review, separating verified developments from the engineering choices they should change.