Authentication Patterns for Modern Web Apps
Authentication is one of those topics where there are many ways to do it, and the "right" way depends heavily on your context.
The Options
Session-Based Auth
The classic approach. Server stores session data; client gets a session ID cookie.
Pros: Simple to invalidate, server has full control Cons: Doesn't scale horizontally without session sharing
JWT (JSON Web Tokens)
Stateless tokens signed by the server.
Pros: Stateless, scales well, can be used across services Cons: Hard to invalidate before expiry
OAuth / Social Login
Delegate auth to a provider (Google, GitHub, etc.)
Pros: No password management, trusted providers Cons: Dependency on third party
What I Chose
For most of my projects, I use JWT with HTTP-only cookies. This gives:
- Stateless scaling benefits of JWT
- XSS protection from HTTP-only cookies
- CSRF protection with SameSite=Lax
// Set JWT in HTTP-only cookie
response.setCookie('token', jwt, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax',
maxAge: 60 * 60 * 24 * 7, // 7 days
})