DEV Community

Cover image for Sessions vs JWT vs Cookies: Understanding Authentication Approaches
Kunal
Kunal

Posted on

Sessions vs JWT vs Cookies: Understanding Authentication Approaches

Whether you are building a small application or a production SaaS, the bare minimum thing you need is authentication.

Over the years, developers have used many technologies to successfully authenticate and authorize users, but the technologies behind it have remained the same: Sessions, JWT, and Cookies.

So in this blog we will study:

  • What sessions are
  • What cookies are
  • What JWT tokens are
  • Stateful vs stateless authentication
  • Differences between session-based auth and JWT
  • When to use each method

Sessions

A session is a temporary memory on the server that remembers who you are.

Since HTTP is stateless, it forgets everything after every request. It doesn't remember if you're logged in or not.

A session fixes this by storing your information on the server. Your browser only sends a Session ID, and the server uses it to recognize you on every request.

How Sessions Work (Step-by-Step)

  1. The user logs in with their email and password.
  2. The server creates a session with a unique Session ID and stores user information (like userId, role, etc.) on the server.
  3. The server sends the Session ID back to the browser as a cookie.
  4. On every new request, the browser automatically sends the Session ID cookie to the server.
  5. The server checks the Session ID, finds the matching session, and retrieves the user's information.

Sessions are stored on the server, usually in memory, a database, Redis, or files.

Note: The browser only stores the Session ID, not the actual user data.


Cookies

Cookies are small text files, not a storage mechanism. (Yes, I learned that while writing this blog.) They are stored by the browser and can hold up to 4 KB of data.

Cookies are generally used to carry access tokens or session IDs with every HTTP request. This helps the server identify the user and keeps the user logged in so they do not have to sign in again whenever they visit a new page.

They are widely used for authentication, tracking, and personalization.

cookie

Credits: https://newsletter.systemdesigncodex.com/p/cookies-vs-sessions-vs-jwt

There are mainly 4 types of cookies:

1. Session Cookies

They exist only during the current browser session until the browser is closed.

Example: Online banking sessions.

const express = require('express');
const session = require('express-session');

const app = express();

app.use(session({
  secret: 'yoursecretkey',
  resave: false,
  saveUninitialized: true,
  cookie: {
    secure: true,
    httpOnly: true,
    maxAge: 60000
  }
}));

app.get('/', (req, res) => {
  req.session.views = (req.session.views || 0) + 1;
  res.send(`Views: ${req.session.views}`);
});

app.listen(3000);
Enter fullscreen mode Exit fullscreen mode

2. Persistent Cookies

They remain on the user's device until they expire based on the expiration date set by the server.

Example: A "Remember Me" option on a social media login keeps you signed in by storing a persistent cookie until it expires or you log out.

const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();

app.use(cookieParser());

app.get('/set-cookie', (req, res) => {
  res.cookie('username', 'John Doe', {
    maxAge: 3600000,
    httpOnly: true,
    secure: true,
    sameSite: 'lax'
  });
  res.send('Persistent cookie set!');
});

app.get('/get-cookie', (req, res) => {
  const username = req.cookies.username;
  res.send(`Username: ${username}`);
});

app.listen(3000, () => console.log('Server running on port 3000'));
Enter fullscreen mode Exit fullscreen mode

3. Secure Cookies

They are transmitted only over HTTPS to prevent interception.

Example: An online shopping site uses a Secure cookie so your login session is sent only over an encrypted HTTPS connection.

res.cookie('sessionId', 'abc123', {
  secure: true,
  httpOnly: true,
  sameSite: 'Strict',
  maxAge: 3600000
});
Enter fullscreen mode Exit fullscreen mode

4. HttpOnly Cookies

They prevent cookies from being accessed via JavaScript, reducing the risk of XSS attacks.

Example: A banking website stores your login token in an HttpOnly cookie, so JavaScript cannot read or steal it.

const express = require('express');
const cookieParser = require('cookie-parser');
const cors = require('cors');

const app = express();

app.use(cors({
  origin: 'http://localhost:3000',
  credentials: true
}));

app.use(cookieParser());

app.post('/login', (req, res) => {
  const token = 'your-jwt-token';

  res.cookie('token', token, {
    httpOnly: true,
    secure: false,
    sameSite: 'strict',
    maxAge: 24 * 60 * 60 * 1000
  });

  res.send({ success: true });
});
Enter fullscreen mode Exit fullscreen mode

JWT Tokens

JWT, also known as JSON Web Token, does not rely on server-side storage like sessions.

Instead, the user information is stored inside the token itself.

JWT tokens

Structure of JWT

A JWT consists of three parts separated by dots (.).

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.
eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.
KMUFsIDTnFmyG3nMiGM6H9FNFUROf3wh7SmqJp-QV30
Enter fullscreen mode Exit fullscreen mode
Header.Payload.Signature
Enter fullscreen mode Exit fullscreen mode
  • Header: Contains metadata about the token, such as the signing algorithm (HS256, RS256) and token type.

  • Payload: Contains the actual data (claims), such as userId, role, and email. It is encoded, not encrypted, so anyone can read it.

  • Signature: Verifies that the token was created by the server and has not been modified. If someone changes the payload, the signature becomes invalid and the token is rejected.

How JWT Works (Step-by-Step)

  1. The user logs in with their email and password.
  2. The server verifies the credentials.
  3. If they're correct, the server creates a JWT containing the user's ID and role.
  4. The JWT is sent back to the client and is usually stored in a cookie.
  5. For every protected request, the client sends the JWT in the Authorization header (or the cookie).
  6. The server verifies the JWT. If it's valid, the request is allowed; otherwise, it's rejected.

Stateful vs Stateless Authentication

Stateful Stateless
Server remembers who you are. Server forgets who you are after every request.
Uses Sessions. Uses JWT.
User data stays on the server. User data stays inside the JWT token.
Browser sends a Session ID. Browser sends the JWT token.
Server looks up the session every time. Server just verifies the token.
Easy to log out (delete the session). Harder to log out (wait for the token to expire or blacklist it).
Good for traditional websites. Good for APIs, mobile apps, and microservices.
Example: Login with Sessions. Example: Login with JWT.

Differences Between Session-Based Authentication and JWT

Session-Based Authentication JWT Authentication
User data is stored on the server. User data is stored inside the JWT token.
Browser stores only the Session ID. Browser stores the entire JWT token.
Server checks the session on every request. Server only verifies the token signature.
Easy to log out by deleting the session. Logout is harder unless the token expires or is blacklisted.
Better for traditional web apps. Better for APIs, mobile apps, and microservices.
More server memory is needed. Less server memory is needed.
Easy to revoke sessions anytime. Tokens remain valid until they expire.
Example: Banking websites. Example: REST APIs and mobile apps.

When to Use Sessions

Use Sessions when you want the server to have full control over user authentication. They're a great choice when security is more important than scalability.

Examples:

  • Online banking
  • E-commerce admin panels
  • Internal company portals

When to Use JWTs

Use JWTs when you need a stateless and scalable authentication system. They're ideal for modern apps and APIs.

Examples:

  • Mobile apps
  • REST APIs
  • Single Page Applications (React, Angular, Vue)
  • Microservices

Thanks for reading! If you enjoyed this blog, you can read more here 👇

Top comments (0)