tezvyn:

Session Authentication: JWT vs. Database

AI-drafted, machine-checkedSource: authjs.devintermediate

Session auth gives users an ID after login. A JWT is a self-contained ID card with their data; a database session is a library card pointing to their record. The key trade-off: JWTs are fast but can't be easily revoked, while database sessions are revocable.

WHY IT EXISTS: Applications need to remember users between visits without forcing a login on every page load. Session management solves this by creating a persistent identity for a user after they authenticate once, allowing them to pick up where they left off.

THE MENTAL MODEL: Think of it as giving a user an ID after they show their credentials. This ID is presented on every subsequent request. The core choice is what kind of ID to issue. Is it a detailed, self-contained ID card (a JWT session) or a simple library card number that requires looking up their record (a Database session)?

HOW IT WORKS: The two main strategies are JWT-based and database-based. A JWT session encodes user data into an encrypted JSON Web Token and stores it in a secure, HttpOnly browser cookie. The server is stateless; it just decrypts this token on each request to identify the user. A Database session stores all user data in a server-side database. It only places a unique, random session ID in the cookie. On each request, the server uses this ID to look up the full session details from the database.

WHEN TO USE IT: Use a JWT session when you need a stateless, fast, and scalable solution, especially across multiple services, and you can tolerate short session expiry times. Use a Database session when you need the ability to revoke sessions instantly (e.g., on password change or 'logout from all devices'), or when you need to store more session data than fits in a cookie.

WHEN NOT TO USE IT: Avoid JWT sessions if immediate session invalidation is a critical security requirement, as a stolen JWT is valid until it expires. The only mitigation is a server-side blocklist, which negates the stateless benefit. Avoid database sessions if you are building a purely stateless application or if the overhead of a database and the latency of lookups on every request are unacceptable.

ONE CANONICAL EXAMPLE: In Next.js, Auth.js defaults to JWT sessions. When a user logs in, it creates an encrypted JWT in an HttpOnly cookie. If you configure Auth.js with a database adapter, it switches to database sessions. It then creates a session record in your database and puts only the session ID in the cookie. This choice is configured via the session.strategy option.

Read the original → authjs.dev

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.