Session Strategies: JWT vs Database Sessions
Auth.js supports two different session-tracking strategies. Let us analyze how they work and when to use them.
1. JWT (Stateless Session) Strategy
By default, Auth.js uses the JWT strategy. When a user signs in, the server generates a JSON Web Token containing the user details, encrypts it, and saves it in a browser cookie.
Advantages
- Stateless: The server does not query the database on incoming requests. This makes it performant and scaleable.
- Serverless Friendly: Works on edge architectures without needing database connection pools.
Disadvantages
- Cannot Revoke Sessions Immediately: Once issued, a JWT is valid until it expires. You cannot sign a user out from a server administration dashboard instantly unless you implement custom blocklists.
2. Database (Stateful Session) Strategy
If you configure a database adapter (such as Prisma Adapter), you can switch to the database session strategy. When a user signs in:
- The server creates a unique session token.
- The server saves the token details inside the
Sessiontable in your database. - The server writes the token string to the client browser cookie.
On every incoming request, Auth.js queries your database to verify if the session token is active.
Advantages
- Real-time Session Revocation: You can immediately delete a session row from the database to sign out a compromised device.
- Accurate Device Tracking: Allows users to manage and inspect all active logged-in device sessions in their profile settings.
Disadvantages
- Database Overhead: Requires database reads on every HTTP page request, which can slow down applications under heavy traffic.
3. Configuring Strategies in auth.ts
Specify the strategy using the session configuration block:
export const { handlers, auth } = NextAuth({
// Configure JWT strategy
session: {
strategy: "jwt",
maxAge: 30 * 24 * 60 * 60, // Session expires after 30 days
},
});Published on Last updated: