Skip to main content

Session vs JWT in Next.js 16: What Changed and What Most Guides Get Wrong

Updated 9 min readMarkdown

Every time someone asks whether to use sessions or JWT for authentication in Next.js, the honest answer is "it depends on what you're building," and then the conversation stalls because most guides never explain what it actually depends on. This one will. By the end you'll know how server sessions work in the Next.js 16 App Router, how JWTs work and why they feel easier at first, where each one quietly breaks, and which one you should reach for on your next project.

How sessions work in Next.js 16 App Router

A server session is simple in concept: the server creates a record (in a database, Redis, or an encrypted cookie) when a user logs in, hands the browser an opaque session ID, and looks that ID up on every request. The user's actual data never leaves the server.

In the App Router, this pattern usually looks like a Server Action that runs on login, sets an HTTP only cookie, and stores the session server side:

"use server";

import { cookies } from "next/headers";
import { createSession } from "@/lib/session";

export async function login(formData: FormData) {
  const user = await verifyCredentials(formData);
  const sessionId = await createSession(user.id);

  (await cookies()).set("session", sessionId, {
    httpOnly: true,
    secure: true,
    sameSite: "strict",
    path: "/",
    maxAge: 60 * 60 * 24 * 7,
  });
}

That httpOnly flag matters more than most tutorials admit. Client side JavaScript cannot read an HTTP only cookie, which closes off the most common attack path against session tokens: cross site scripting, or XSS. If an attacker manages to inject a script into your page, that script still cannot reach the cookie. HTTP only cookies remain exposed to a different attack, cross site request forgery (CSRF), where a malicious site tricks the browser into sending an authenticated request on your behalf. Setting sameSite: "strict" (or at minimum "lax") is the mitigation, and it's the reason you see it in almost every serious session setup.

Route protection then happens in middleware, which runs at the edge before the request ever reaches a page or Server Action:

import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";

export function middleware(request: NextRequest) {
  const session = request.cookies.get("session");
  if (!session && request.nextUrl.pathname.startsWith("/dashboard")) {
    return NextResponse.redirect(new URL("/login", request.url));
  }
  return NextResponse.next();
}

For server sessions this middleware check is usually just presence, not validation. The real lookup (does this session ID still exist, is it expired, has it been revoked) happens where the session is actually created and read, because middleware runs on the edge runtime and shouldn't be doing a database round trip on every request.

How JWTs work and why they feel easier

A JSON Web Token bundles the user's claims (id, role, expiry) into a signed payload the server can verify without a database lookup. That's the appeal: no session store, no extra round trip, works the same whether you're serving a web page or an API.

JWT based auth in the Next.js 16 App Router leans on the same primitives as sessions: Server Actions issue the token on login and logout, middleware protects routes, and cache() lets you share the decoded session across server components in a single request without re verifying the token on every read.

import { cache } from "react";
import { jwtVerify } from "jose";

export const getSession = cache(async () => {
  const token = (await cookies()).get("token")?.value;
  if (!token) return null;
  try {
    const { payload } = await jwtVerify(token, secret);
    return payload;
  } catch {
    return null;
  }
});

Because cache() dedupes the call per request, you can call getSession() from a layout, a page, and a nested component and only pay the verification cost once. That's a genuine ergonomic win, and it's the reason JWT patterns keep getting recommended in App Router tutorials.

The catch is storage. If you keep the JWT in localStorage so client components can read it directly, it's fully exposed to XSS: any script that runs on your page can read localStorage and exfiltrate the token, no cookie flags involved. Most production ready Next.js JWT setups avoid this entirely by keeping the token in an HTTP only cookie too, which closes the XSS gap but reopens the question of why you're using a JWT instead of an opaque session ID in the first place.

The security tradeoffs most guides skip

This is the part most JWT vs session tutorials gloss over, so it's worth stating plainly: the tradeoff isn't really about tokens versus sessions, it's about statelessness versus revocation.

A session is trivial to revoke. Delete the record server side, and the user is logged out everywhere, instantly, including on every device and every open tab. A JWT is valid until it expires, full stop, because the whole point is that the server doesn't need to check a store to trust it. If someone steals a JWT with a seven day expiry, that token works for seven days unless you build a separate revocation list, at which point you've reintroduced a server side lookup and lost the statelessness that made JWTs attractive.

That single property, token revocation, is usually the deciding factor:

  • If you need to instantly kill a compromised session (a stolen device, a fired employee, a password reset), you want the immediate, guaranteed revocation that server sessions give you for free.

  • If your access tokens are short lived (a common pattern is 15 minutes) and paired with a refresh token you can revoke, JWTs get a workable approximation of instant revocation without giving up statelessness for the access token itself.

Combine that with the XSS and CSRF picture from earlier and you get a fuller comparison: sessions in HTTP only cookies are safe from XSS and need SameSite for CSRF; JWTs in localStorage are exposed to XSS with no CSRF risk; JWTs in HTTP only cookies get the same protection profile as sessions but without the easy revocation.

When to use sessions

Reach for server sessions when you're building a first party web app where the browser is the only client that matters. Server sessions let you revoke access immediately, they keep zero sensitive data on the client, and they pair naturally with the App Router's server first model, since a Server Component can just read the session cookie and hit your session store directly without shipping any auth logic to the client.

They're also the safer default when your team is still building auth expertise: there's less surface area to get wrong, because the hard cryptographic decisions (signing algorithm, key rotation, expiry tuning) belong to whatever session library or database you're using instead of your own code.

When JWTs are the right call

JWTs earn their complexity in a specific shape of system: stateless APIs consumed by a mobile app or a third party integration, or a microservices setup where multiple services need to trust a user's identity without every single service making a call back to a central session store. In that world, a signed token that any service can verify independently is exactly the right tool, because the alternative (every microservice querying a shared session store on every request) is slower and adds a hard dependency between services that otherwise shouldn't need to know about each other.

If your Next.js app is purely first party, though, that stateless benefit mostly evaporates. You're not passing the token to another service, so you've taken on JWT's revocation weaknesses without collecting the payoff that makes them worth it elsewhere.

What most teams choose today

Ask around and you'll notice a pattern: most current Next.js auth stacks, including Auth.js (formerly NextAuth), Better Auth, and Supabase Auth, default to server sessions rather than JWTs for first party web apps. That's not an accident. It reflects the tradeoff above playing out at scale: for a typical Next.js app talking to itself, the revocation and simplicity of sessions win more often than the statelessness of JWTs pays off.

If you're starting a new App Router project and don't have a strong reason to reach for JWTs (a public API, a mobile client, a microservices boundary), start with server sessions through Auth.js or a similar library, store the session cookie as HTTP only with SameSite set to strict, and only bring in JWTs later if a genuine stateless use case shows up.

FAQ

Should I use sessions or JWT in Next.js? For a standard first party Next.js web app, use sessions. They're easier to revoke instantly, keep no sensitive payload on the client, and fit the App Router's server first design. Reach for JWTs only when you have a real stateless requirement, like a public API or a mobile client that needs to verify identity without hitting your server on every call.

What is the difference between session based and JWT authentication? Session based authentication stores the user's state on the server and hands the browser an opaque ID that means nothing on its own; the server looks up that ID on every request. JWT authentication bundles the user's claims into a signed token the server can verify without a lookup, trading a database round trip for a token that can't be revoked before it expires.

Is JWT secure for Next.js applications? It can be, but only with the right storage choice. A JWT kept in localStorage is exposed to XSS, since any script running on the page can read it. A JWT kept in an HTTP only cookie is protected from XSS the same way a session cookie is, and needs the same SameSite protection against CSRF. The security question isn't really about JWT versus sessions as concepts; it's about where the token or session ID lives in the browser.

Good breakdown, the revocation vs statelessness framing is the clearest way I've seen this explained. One thing worth adding on the middleware side, since it's only checking presence not validity for sessions, that means a stolen but not-yet-revoked session cookie sails right through the edge check and only gets caught at the actual session store lookup deeper in the request. Worth being explicit in the writeup that middleware here is a redirect-for-UX layer, not a security boundary, people sometimes read "middleware protects routes" and assume it's doing more than it is.

More from this blog