Topics & Navigation

Web Development

JWT vs Sessions vs OAuth2: Which Authentication Should You Use?

Table of contents (17 sections)

In short: these three are not direct competitors. Sessions keep the login state on the server and give the browser a cookie. A JWT is a signed token format that carries the claims with it. OAuth2 is a protocol for letting one application act on behalf of a user in another; with OpenID Connect on top, it also handles login. For a classic web app, server-side sessions in a secure cookie are the simplest safe choice. Use tokens for APIs and mobile clients, and OAuth2 with OpenID Connect for “sign in with Google” or single sign-on.

Few topics cause as much confusion as authentication. Articles pit “JWT vs sessions” against each other, then add OAuth2 as if it were a third option, and developers walk away with the wrong idea. This guide explains what each one is for, compares them honestly, lists the mistakes that cause real vulnerabilities and ends with a decision guide.

Prerequisites

  • Basic knowledge of HTTP, cookies and headers
  • A web application or API you want to protect (any language)
  • A rough idea of your clients: a browser, a mobile app, other servers, or all of them

Three different things

Sessions: state on the server

After the user logs in, the server creates a session record, stores it (in memory, a database or Redis) and sends the browser a random session ID in a cookie. On each request, the browser sends the cookie and the server looks up the session.

Strengths: you can end a session instantly (logout, password change, suspicious activity), the browser never holds readable data, and cookies are handled by the browser automatically. Weaknesses: you need shared session storage once you run several servers, and cookie-based sessions require protection against cross-site request forgery.

JWT: a signed token that carries claims

A JSON Web Token contains a header, a payload of claims (such as user ID and expiry) and a signature. Any service holding the right key can verify it without a database call. That makes JWTs useful when several services or clients need to trust the same identity.

Two facts are often misunderstood. The payload is encoded, not encrypted, so anyone who holds the token can read it. And a JWT cannot be revoked by itself before it expires, unless you add server-side state, which defeats part of the point.

OAuth2 and OpenID Connect: delegation and login

OAuth2 lets a user grant an application limited access to their data in another service without sharing a password. It is about authorization. OpenID Connect adds an identity layer, so your app learns who the user is. When you add “Sign in with Google” or use an identity provider such as Keycloak, you are using OAuth2 and OpenID Connect. Tokens issued by that flow are often JWTs, which is another reason the terms get mixed up.

Comparison

| Question | Server-side sessions | JWT access tokens | OAuth2 / OpenID Connect |
|—|—|—|—|
| What is it? | Server state plus an opaque cookie | A signed, self-contained token | A protocol for delegated access and login |
| Where is state? | On the server | In the token | At the identity provider |
| Immediate revocation | Easy | Hard without extra state | Depends on the provider and token lifetime |
| Best for | Server-rendered sites, dashboards | APIs, mobile apps, service-to-service | Third-party login, single sign-on |
| Main risk | CSRF, session fixation | Token theft, long lifetimes, wrong validation | Misconfigured flows and redirect URIs |

Which one should you use?

  1. A website with its own login, rendered by your server or used by your own front end on the same domain: use sessions with a secure cookie. It is the least error-prone option.
  2. A single-page app with your own API: keep it simple. Cookie-based sessions still work well when the front end and API share a site. If you need tokens, use short-lived access tokens and keep the refresh mechanism out of reach of JavaScript.
  3. A mobile app or a public API: use short-lived access tokens, with refresh tokens that rotate, and store them in the platform’s secure storage.
  4. “Sign in with Google”, GitHub or a company directory: use OAuth2 with OpenID Connect, with the authorization code flow and PKCE.
  5. Several applications that should share one login: use an identity provider (for example Keycloak) and OpenID Connect. See our guide to authenticating NuxtJS with Keycloak.
  6. A small app that wants everything built in: a backend such as PocketBase offers authentication and OAuth2 out of the box, as shown in our PocketBase authentication tutorial.

Whatever library you use, make sure the session cookie has the right flags. Here is the idea in an Express application:

jsapp.use(session({
  name: 'sid',
  secret: process.env.SESSION_SECRET,
  resave: false,
  saveUninitialized: false,
  cookie: {
    httpOnly: true,   // not readable by JavaScript
    secure: true,     // only sent over HTTPS
    sameSite: 'lax',  // reduces CSRF risk
    maxAge: 1000 * 60 * 60 * 8
  }
}));

Regenerate the session ID after login, set an expiry, and add an idle timeout, as shown in our guide to session idle in JavaScript. The OWASP session management cheat sheet lists more protections.

Verifying a JWT correctly

If you use JWTs, validate more than the signature. Fix the allowed algorithm, and check the issuer, audience and expiry:

jsimport jwt from 'jsonwebtoken';
 
const payload = jwt.verify(token, process.env.JWT_SECRET, {
  algorithms: ['HS256'],
  issuer: 'https://api.example.com',
  audience: 'web-app',
});

Keep access tokens short, for example 5 to 15 minutes. Use a separate, longer-lived refresh token that you can revoke on the server, and rotate it every time it is used.

The most common JWT mistakes

  • Storing tokens in localStorage. Any cross-site scripting bug lets an attacker read them. Prefer HttpOnly cookies or in-memory storage with a refresh cookie.
  • Accepting any algorithm. Always specify the algorithms you allow, so a forged token that claims to be unsigned is rejected.
  • Long expiry. A stolen token stays valid until it expires. Short lifetimes limit the damage.
  • Sensitive data in the payload. Anyone can decode it. Store identifiers, not secrets or personal data.
  • No logout story. Decide how you will revoke access: short lifetimes, a deny list or server-side refresh tokens.
  • Skipping audience and issuer checks. A token meant for another service might be accepted by yours.

OAuth2 mistakes to avoid

  • Using the old implicit flow. Use the authorization code flow with PKCE, defined in RFC 7636.
  • Accepting loose redirect URIs. Register exact URLs and reject everything else.
  • Treating an access token as proof of identity. Use the ID token from OpenID Connect for that, and validate it.
  • Requesting more scopes than you need.

FAQ

Are JWTs more secure than sessions?

No. Neither is inherently more secure. Sessions are simpler to revoke and harder to misuse in a browser, while JWTs are practical across services. Security depends on how you configure and store them.

Can I use JWT and sessions together?

Yes. A common pattern is a short-lived JWT for API calls and a server-side session or refresh token behind it. Just make sure you understand where each piece of state lives.

Do I need OAuth2 for my own login page?

Not necessarily. If users sign up with email and password on your site, a session is enough. Use OAuth2 when you let people sign in with another provider or when several apps share an identity.

What about passkeys and multi-factor authentication?

They improve how users prove who they are, and they work with any of these approaches. After login, you still need a session or a token to remember the user.

Next steps

Pick the simplest option that fits your clients, then add protections: secure cookies, short lifetimes, rate limiting and monitoring. To implement it quickly with a ready-made backend, follow PocketBase authentication with JavaScript, and review the code you ship with our checklist for AI-generated code.