Auth.js and Session Strategies in Next.js
Authentication in a Next.js app sits across three runtimes at once: the browser holds a cookie, middleware makes fast decisions at the edge, and Server Components read the final session on the server. Auth.js â formerly NextAuth.js â is the framework-native library that stitches those pieces together. It handles the OAuth redirect dance, issues signed session cookies, and exposes the session to every layer of the App Router through one configuration file.
Getting it working in ten minutes is easy. Getting the session strategy, middleware boundaries, and database flows right for a production product is where teams stumble. This lesson explains how Auth.js actually issues and verifies sessions, when to choose JWT versus database sessions, how to protect routes without leaking tokens to the client bundle, and how callbacks let you shape the session object that the rest of your code depends on.
Prerequisites
- !Working Next.js App Router project
- !Understanding of cookies, redirects, and OAuth at a conceptual level
- !Access to at least one OAuth app credentials (GitHub or Google)
What You'll Learn
- 1Wire Auth.js with one or more OAuth providers
- 2Decide between JWT and database session strategies
- 3Protect route segments with middleware and server checks
- 4Extend the session with custom claims such as user id and role
The request flow, end to end
Before configuring anything, it helps to see what happens when a user clicks "Sign in with GitHub". The browser is redirected to GitHub, GitHub redirects back to your callback route with a code, Auth.js exchanges the code for tokens, creates or finds a user row, and sets a session cookie on the response. From that point on, every request carries the cookie, and your code reads the session without ever talking to GitHub again.
// app/api/auth/[...nextauth]/route.js
import NextAuth from 'next-auth';
import GitHub from 'next-auth/providers/github';
import Google from 'next-auth/providers/google';
import Credentials from 'next-auth/providers/credentials';
import { db } from '@/lib/db';
import { verifyPassword } from '@/lib/hash';
const handler = NextAuth({
providers: [
GitHub({
clientId: process.env.GITHUB_ID,
clientSecret: process.env.GITHUB_SECRET,
}),
Google({
clientId: process.env.GOOGLE_ID,
clientSecret: process.env.GOOGLE_SECRET,
}),
Credentials({
credentials: {
email: { label: 'Email', type: 'email' },
password: { label: 'Password', type: 'password' },
},
async authorize(credentials) {
const user = await db.user.findUnique({
where: { email: credentials.email },
});
if (!user) return null;
const ok = await verifyPassword(credentials.password, user.passwordHash);
return ok ? { id: user.id, email: user.email, name: user.name } : null;
},
}),
],
session: { strategy: 'jwt' },
callbacks: {
async jwt({ token, user }) {
if (user) {
token.userId = user.id;
token.role = user.role ?? 'member';
}
return token;
},
async session({ session, token }) {
session.user.id = token.userId;
session.user.role = token.role;
return session;
},
},
});
export { handler as GET, handler as POST };
The catch-all route segment [...nextauth] is deliberate: Auth.js owns a family of subpaths such as sign-in, callback, and session, and one handler dispatches them all. Keeping every provider in this single file also means the env var surface stays auditable â one place to confirm that every secret the auth flow needs is actually present in the deployment environment.
JWT or database sessions
The strategy choice determines where revocation lives. A JWT session is self-contained: the cookie carries a signed token with the claims, and the server verifies the signature without a database read. It is fast and works well on the edge, but a leaked or revoked token stays valid until it expires unless you add a denylist. A database session stores a random id in the cookie and the record in your database, so revocation is a row update â at the cost of a lookup on every request.
| Concern | JWT strategy | Database strategy |
|---|---|---|
| Verify without a database | Yes | No |
| Instant logout-everywhere | Hard; needs denylist or short TTL | Easy; delete the row |
| Session size limits | Token must stay cookie-sized | Arbitrary data in the row |
| Edge middleware compatibility | Strong | Limited unless the DB is edge-reachable |
| Best fit | Most apps, long-lived tokens | High-security, admin, finance |
A pragmatic default for SaaS products is JWT with rotating expiry plus a server-side revocation table consulted on sensitive actions. Pure JWT with no revocation path is a poor fit for anything where "log this user out of all devices" is a compliance requirement.
Reading the session in Server Components
Client-side useSession works, but the App Router's superpower is reading the session on the server during render. That keeps the check out of the client bundle and lets you pass the user id straight into data queries.
// app/settings/page.js
import { auth } from '@/auth';
import { redirect } from 'next/navigation';
import { db } from '@/lib/db';
export default async function SettingsPage() {
const session = await auth();
if (!session?.user) {
redirect('/login');
}
const profile = await db.user.findUnique({
where: { id: session.user.id },
select: { email: true, name: true, role: true },
});
return (
<main>
<h1>Account settings</h1>
<p>Signed in as {profile.email}</p>
<p>Role: {profile.role}</p>
</main>
);
}
Calling auth() inside a Server Component is the idiomatic App Router approach. The redirect for unauthenticated users belongs here for defense in depth, even when middleware already guards the path â middleware can be bypassed by misconfiguration, and the page-level check is the last gate before data is touched.
Middleware as the first gate
Middleware runs before the request reaches your pages, on the edge, with sub-millisecond overhead. Auth.js ships a middleware wrapper that checks the session cookie and redirects or 401s accordingly. Use it to keep anonymous users out of entire trees cheaply; do not use it as your only authorization layer.
// middleware.js
export { auth as middleware } from '@/auth';
export const config = {
matcher: ['/settings/:path*', '/admin/:path*', '/api/private/:path*'],
};
For role checks, the middleware callback can inspect the token's role claim and redirect unauthorized users to a 403 page. Keep matcher patterns tight: running auth middleware on every static asset wastes edge invocations and adds latency to images and chunks.
Callbacks are where the real design lives
Most Auth.js customization happens in three callbacks. signIn decides whether a user may log in at all â for example, blocking free-tier signups from a waitlist or refusing emails outside your company domain. jwt runs on token creation and refresh, and is the right place to load role, plan, or organization id once rather than on every read. session copies claims from the token onto the session object that your components see. Keeping slow lookups in jwt with a cached write avoids turning every page render into a user-table query.
Production pitfalls
Real incidents cluster around a few themes: the session callback forgetting to copy user.id, so every database query filters on undefined; credentials providers enabled in production without rate limiting, inviting credential stuffing; and the secret left at its development value, invalidating every session when it finally rotates. Another quiet bug is reading the session in middleware and assuming pages are protected â matcher gaps leave whole sections open, and only page-level checks catch it.
Signing out everywhere and session hygiene
Logout sounds trivial and hides three distinct operations. Clearing the client state â the session cookie â ends the browser's participation. Invalidating the server-side record ends the session's validity for database strategies. And rotating or denying the token ends it for JWT strategies. A logout button that only does the first leaves a stolen cookie valid until expiry, which is why high-security products keep a revocation timestamp on the user record and check it in the jwt callback: even a correctly signed token whose user was revoked seconds ago fails verification on the next request. Session hygiene extends to issuance as well. Set explicit maxAge values rather than library defaults, enable token rotation so each refresh issues a fresh token, and cap concurrent sessions per account if abuse patterns warrant it. On the cookie itself, mark it httpOnly and secure â Auth.js does this by default â and set sameSite to lax so the cookie rides top-level navigations but not cross-site form posts. Each of these settings is one line; together they decide how much a leaked cookie is worth to an attacker.
Common Mistakes
Trusting middleware alone to protect every private route
Fix: Call auth() in each protected Server Component as well; middleware is an optimization, not the sole gate.
Exposing the raw JWT or provider tokens to the client
Fix: Strip provider access tokens in the jwt callback unless you genuinely need them, and never attach them to the session.
Enabling the credentials provider with no rate limiting
Fix: Add per-IP and per-account throttling at the edge, and consider disabling credentials in favor of OAuth or magic links.
Logging out only on the client
Fix: Server-side sign-out must invalidate the session record or rotate the token; clearing localStorage alone does nothing for cookie sessions.
Best Practices
- Store only claims you need in the JWT: id, role, expiry â fetch the rest on demand
- Rotate AUTH_SECRET with a planned dual-verify window so sessions do not all die at once
- Audit matcher patterns whenever you add a new private route tree
- Log sign-in, sign-out, and failed-auth events with the user id for security review
Interview Questions
Q1: Why can middleware not protect a route by itself?
Matcher misconfiguration, header spoofing of internal rewrites, or direct route-handler access can skip middleware. A server-side auth() check at the data layer is the authoritative gate.
Q2: How do you revoke a JWT session early?
Use a short token TTL with refresh rotation, or keep a server-side denylist or last-seen table consulted on sensitive operations. Pure self-contained JWTs cannot be revoked by deleting a row.
Q3: Where should a custom user id be added to the session?
In the jwt callback when the user first signs in, then copied onto the session in the session callback so Server Components can read session.user.id.
Key Takeaways
- Auth.js owns the OAuth redirect flow and issues the signed session cookie your app reads everywhere.
- JWT sessions are fast and edge-friendly; database sessions make revocation trivial. Choose based on your logout and compliance needs.
- Read sessions in Server Components with auth() and treat middleware as a cheap first gate, not the only one.
- The jwt and session callbacks are where custom claims like id and role are loaded and exposed.
- Protect credentials endpoints with rate limiting and keep AUTH_SECRET out of version control.