Choosing between JWT, OAuth, and sessions for authentication is maddening because people conflate different concerns. Sessions are simple and stateful. JWT is stateless but has security gotchas. OAuth is for delegated access, not authentication. This post breaks down what each one actually does, where they fit, and why your choice depends on your specific constraints, not hype.
The Meeting That Confused Everything
A junior dev said “we should use JWT for security.” A senior engineer said “sessions are more secure.” A crypto person said “we should use OAuth.” Everyone walked out confused. I realized nobody was actually using the same definitions.
That’s because authentication is being discussed as one thing when it’s actually three different problems. Sessions, JWT, and OAuth solve different problems. Once you separate them, the confusion disappears.
What’s Actually Happening When Someone Logs In
Authentication is verifying who someone claims to be. It works by validating credentials (username/password, email/code, biometric, etc.) and then maintaining proof of that identity. The key benefit is knowing who’s making requests to your system.
Once authenticated, you need some way to prove that identity on subsequent requests. That’s where sessions, JWT, and OAuth come in—they’re different strategies for maintaining that proof.
Think of it like a concert venue: authentication is showing your ID at the door. The proof mechanism (sessions, JWT, OAuth) is the wristband you wear to prove you already checked in.
Sessions: The Traditional Approach
Sessions have been around forever because they work. Here’s how they work:
- User logs in with username and password
- Server creates a session, stores it in memory or database
- Server sends back a session ID in a cookie
- Browser automatically includes the cookie on every request
- Server validates the session ID and allows the request
Implementation is straightforward:
// Express with express-session
import express from 'express';
import session from 'express-session';
import passport from 'passport';
import LocalStrategy from 'passport-local';
const app = express();
app.use(session({
secret: 'your-secret-key',
resave: false,
saveUninitialized: false,
cookie: {
httpOnly: true, // Can't be accessed by JavaScript
secure: true, // HTTPS only
sameSite: 'strict', // CSRF protection
maxAge: 1000 * 60 * 60 * 24 // 24 hours
}
}));
app.post('/login', (req, res) => {
const user = authenticateUser(req.body.username, req.body.password);
if (!user) {
return res.status(401).json({ error: 'Invalid credentials' });
}
// Create session
req.session.userId = user.id;
req.session.email = user.email;
res.json({ success: true, message: 'Logged in' });
});
app.get('/profile', (req, res) => {
// Session is automatically validated from cookie
if (!req.session || !req.session.userId) {
return res.status(401).json({ error: 'Not authenticated' });
}
const user = db.users.findById(req.session.userId);
res.json(user);
});
app.post('/logout', (req, res) => {
req.session.destroy((err) => {
if (err) return res.status(500);
res.json({ success: true });
});
});
Why Sessions Work
Sessions are simple. The server maintains state. If you need to invalidate a session immediately (user logged out, permissions changed, suspicious activity), you just delete the session record. Done. Instantly effective.
Cookies are automatically sent by the browser with every request, so you don’t have to remember to include headers. CSRF tokens can be included in forms to prevent cross-site attacks. Sessions are stateful but that’s a feature for security—the server has complete control.
Why Sessions Have Limitations
Sessions require server-side storage. If you have one server, fine. If you have multiple servers behind a load balancer, you need shared session storage (Redis, database). Now you have a bottleneck and a dependency.
Sessions don’t work well for mobile apps. Mobile apps don’t automatically send cookies like browsers do. You’d need to manually manage session tokens, which defeats the purpose.
Sessions also make it harder to have separate frontend and backend domains. CORS requests with credentials are finicky.
JWT: The Modern Stateless Approach
JWT (JSON Web Token) flips the model: instead of storing session data on the server, you encode everything into the token itself and have the server verify it.
Here’s how JWT works:
- User logs in with username and password
- Server creates a JWT: a signed token containing user claims (id, email, permissions, etc.)
- Server sends the JWT to the client
- Client stores it (localStorage, sessionStorage, or memory)
- Client includes it in the Authorization header on requests:
Authorization: Bearer {token} - Server verifies the signature and reads the claims
Implementation:
// Using jsonwebtoken
import jwt from 'jsonwebtoken';
const JWT_SECRET = 'your-secret-key';
app.post('/login', (req, res) => {
const user = authenticateUser(req.body.username, req.body.password);
if (!user) {
return res.status(401).json({ error: 'Invalid credentials' });
}
// Create JWT
const token = jwt.sign(
{
userId: user.id,
email: user.email,
role: user.role
},
JWT_SECRET,
{ expiresIn: '24h' }
);
res.json({ token });
});
app.get('/profile', (req, res) => {
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return res.status(401).json({ error: 'No token provided' });
}
const token = authHeader.slice(7);
try {
const claims = jwt.verify(token, JWT_SECRET);
// claims.userId, claims.email, claims.role are available
const user = db.users.findById(claims.userId);
res.json(user);
} catch (err) {
return res.status(401).json({ error: 'Invalid token' });
}
});
app.post('/logout', (req, res) => {
// JWT logout is a client operation: delete the token
// But if you need to revoke immediately, you'd maintain a blacklist
res.json({ success: true });
});
Why JWT Is Popular
No server state. You can validate a JWT without storing anything. Perfect for distributed systems, microservices, and mobile apps. The client includes the token, the server verifies it, done.
JWT works across domains and doesn’t require cookies. You can have your frontend on example.com and API on api.example.com without CORS headaches.
JWT’s Security Gotchas
Here’s where JWT gets tricky. People assume “signed token” means “secure token.” It doesn’t. A JWT is signed (you can verify it hasn’t been tampered with) but it’s not encrypted. You can base64-decode a JWT and read all the claims. Never put sensitive data in a JWT.
// BAD: Never do this
const token = jwt.sign(
{
userId: user.id,
password: user.password, // EXPOSED
creditCard: user.creditCard // EXPOSED
},
JWT_SECRET
);
// GOOD: Only include what you need to verify identity
const token = jwt.sign(
{
userId: user.id,
email: user.email,
role: user.role
},
JWT_SECRET
);
Logout is also harder with JWT. With sessions, you delete the session and it’s immediately invalid. With JWT, the token is valid until it expires. If a user logs out but the token doesn’t expire for 24 hours, they could still use it if someone steals it.
You can maintain a token blacklist (a database of revoked tokens), but now you’re adding state again, which defeats the JWT advantage.
Token storage matters. Where do you store the JWT on the client? localStorage is vulnerable to XSS attacks—malicious JavaScript can read it. Cookies are safer from XSS but require httpOnly flag and CORS setup. Some people store it in memory (lost on refresh) or sessionStorage (cleared when tab closes).
There’s no perfect answer. Each choice has trade-offs.
JWT Refresh Tokens Pattern
A common pattern addresses the expiration problem:
// Step 1: Login returns two tokens
app.post('/login', (req, res) => {
const user = authenticateUser(req.body.username, req.body.password);
const accessToken = jwt.sign(
{ userId: user.id, email: user.email },
JWT_SECRET,
{ expiresIn: '15m' } // Short-lived
);
const refreshToken = jwt.sign(
{ userId: user.id },
REFRESH_SECRET,
{ expiresIn: '7d' } // Long-lived
);
// Store refresh token in httpOnly cookie or database
db.refreshTokens.insert({ userId: user.id, token: refreshToken });
res.json({ accessToken, refreshToken });
});
// Step 2: Access token expires, client uses refresh token to get new one
app.post('/refresh', (req, res) => {
const { refreshToken } = req.body;
try {
const claims = jwt.verify(refreshToken, REFRESH_SECRET);
const stored = db.refreshTokens.findOne({ token: refreshToken });
if (!stored) {
throw new Error('Token revoked');
}
// Issue new access token
const newAccessToken = jwt.sign(
{ userId: claims.userId },
JWT_SECRET,
{ expiresIn: '15m' }
);
res.json({ accessToken: newAccessToken });
} catch (err) {
res.status(401).json({ error: 'Invalid refresh token' });
}
});
// Step 3: Logout revokes the refresh token
app.post('/logout', (req, res) => {
const { refreshToken } = req.body;
db.refreshTokens.deleteOne({ token: refreshToken });
res.json({ success: true });
});
This pattern gives you the best of both: short-lived access tokens (minimize damage if stolen) and a revocation mechanism (logout is immediate).
OAuth: Delegated Access, Not Authentication
This is where most confusion happens. OAuth is not an authentication protocol. It’s an authorization protocol for delegated access.
OAuth lets you say: “Hey, instead of trusting this random app with my password, I’ll let Google/GitHub/Facebook verify my identity, and I’ll give this app permission to access specific resources on my behalf.”
It’s used for things like “Sign in with Google” or “Sign in with GitHub.”
The OAuth Flow
// Using passport-google-oauth20
import GoogleStrategy from 'passport-google-oauth20';
passport.use(
new GoogleStrategy(
{
clientID: 'your-client-id',
clientSecret: 'your-client-secret',
callbackURL: '/auth/google/callback'
},
(accessToken, refreshToken, profile, done) => {
// profile contains user info from Google
let user = db.users.findOne({ googleId: profile.id });
if (!user) {
// First time: create user
user = db.users.insert({
googleId: profile.id,
email: profile.emails[0].value,
name: profile.displayName
});
}
done(null, user);
}
)
);
// Step 1: Redirect to Google
app.get('/auth/google',
passport.authenticate('google', { scope: ['profile', 'email'] })
);
// Step 2: Google redirects back with auth code
app.get('/auth/google/callback',
passport.authenticate('google', { failureRedirect: '/login' }),
(req, res) => {
// User is authenticated
req.session.userId = req.user.id;
res.redirect('/dashboard');
}
);
OAuth vs. Sessions vs. JWT
OAuth is about getting the initial proof of identity. Once the user is authenticated via OAuth, you still need to maintain that authentication—using either a session or JWT.
Most “Sign in with Google” implementations create a session after successful OAuth authentication. The OAuth part is just the login mechanism.
Comparing Honestly: Sessions vs. JWT
| Criteria | Sessions | JWT |
|---|---|---|
| Server Storage | Requires storage | Stateless |
| Logout | Instant (delete session) | Requires blacklist or expiration |
| Scaling | Needs shared storage (Redis) | No dependencies |
| Mobile Apps | Awkward (cookies not auto-sent) | Natural (header-based) |
| Cross-Domain | CORS + credentials = complex | Simple headers |
| Revocation Speed | Instant | On next token refresh |
| Data Sensitivity | Safe (server-side) | Exposed (client-side) |
For a traditional web application (one server, browser clients, simple auth): sessions win. For distributed systems, microservices, or mobile apps: JWT wins. For adding “login with GitHub” to any app: OAuth handles the login, then use sessions or JWT to maintain it.
What I Actually Choose (And Why)
For most projects I work on:
Traditional web apps: Sessions with Redis. Simple, secure, fast revocation. The Redis dependency is worth it.
Mobile apps or multi-domain APIs: JWT with refresh tokens. Short-lived access token (15 minutes), long-lived refresh token (7 days). If I need to revoke a user instantly, I maintain a blacklist for refresh tokens only.
Login mechanisms: OAuth (Google, GitHub, whatever). But only to prove identity. Once authenticated, I use sessions or JWT depending on the rest of the system.
Microservices: JWT between services. Each service validates the JWT without calling a central auth service. This reduces coupling.
The worst mistake is picking one because “it’s modern” or “it’s secure.” Pick it because it fits your constraints. Know the trade-offs. Sessions are old-school but work. JWT is trendy but has gotchas. OAuth is for delegated access, not a replacement for either.
FAQ
Is JWT actually secure?
JWT is cryptographically signed (you can verify it hasn’t been tampered with), but it’s not encrypted. Anyone can read the claims. It’s secure from tampering but not from exposure. Use HTTPS and be careful about what you put in the token.
Why use JWT if sessions are simpler?
Sessions require server storage and don’t scale well across multiple servers without shared infrastructure. JWT is stateless and scales infinitely. But if you have one or two servers and don’t mind Redis, sessions are simpler.
Can I use both sessions and JWT?
Absolutely. Some systems use sessions for logged-in users and JWT for API clients. Others use JWT with a session for persistence. Mix and match based on your needs.
What about httpOnly cookies for JWT?
Store the JWT in an httpOnly cookie to protect from XSS. The browser will include it automatically like a session. This gives you JWT’s stateless benefits plus cookie convenience. Some people call this “JWT but with cookies,” which is fine.
Should I rotate JWTs?
Not required if they’re short-lived (15 minutes). If they’re long-lived (24+ hours), rotation is good practice. The refresh token pattern handles this naturally.
How do I log out with JWT?
Option 1: Let the token expire naturally (if short-lived). Option 2: Client deletes the token. Option 3: Server maintains a blacklist of revoked tokens. The first two are best for stateless systems. The third requires state again.
Is OAuth needed for user login?
No. OAuth is for “login with third-party.” Traditional login (email/password) uses sessions or JWT directly. OAuth is convenient if you want to avoid managing passwords.
What’s the most secure approach?
Sessions with proper HTTPS, secure cookies, and CSRF tokens. The server controls everything. But “most secure” isn’t the only criterion. You also need to scale, support mobile apps, and keep complexity reasonable. Security-first thinking can paralyze you. Find the right balance.
The real answer is: none of these approaches is universally right. Sessions are battle-tested and straightforward. JWT is modern and scales. OAuth solves a different problem. Pick based on your actual constraints, not dogma. And stop letting people tell you one is “more secure”—they solve different problems with different security models.