Session VS Cookie Vs JWT

Session VS Cookie Vs JWT

# webdev# programming# productivity# javascript
Session VS Cookie Vs JWTShivam Yadav

yooo its me shivam hii i am a developer and todays topic of blog is what are these things...

yooo its me shivam

hii i am a developer

and todays topic of blog is what are these things (session, cookie and jwt)

and without wasting time let move to actual topic


first let see the problem statement

Authentication............ ?

everything is happening because of this big word

so whenever the user login the user is given the access to the protected routes like:

  • /dashboard
  • /settings
  • /profile

and as u know HTTP is stateless

then how will u maintain this state of user being login

like with each request if we ask user to login he might get irritated and will not use the website

and to avoid this thing

these things were born 😭

there are different use cases of session and cookie but i will be more focusing on authentication


First Let See The System Design Of Session + Cookies

first user login by putting credential

the server will create a session_id

now the session_id will be stored on the DB related to user

and after that the session_id is sent to user browser

now where the browser will store this session_id?

the designed answer would be:

cookie

and whenever the req/res happens between the server and user browser will send the cookie along with the HTTP request

and when that request is received the server will first take the session_id and check in the DB that whose session is this and that session is valid or not

and if everything is checked the access is provided

and done

this is the Auth happening in back 90's 😭


Visual Flow Of Session Authentication

User Login
    ↓
Server Creates Session ID
    ↓
Session Stored In DB/Memory
    ↓
Session ID Sent In Cookie
    ↓
Browser Stores Cookie
    ↓
Every Request Sends Cookie
    ↓
Server Verifies Session
    ↓
Access Granted
Enter fullscreen mode Exit fullscreen mode

now really understand the session and cookie in detail ?


Cookies

Definition

A cookie is a small piece of data that a server sends to the user’s web browser.

The browser may store it and send it back with subsequent requests to the same server.

now this definition would make sense after that long prolog 😭


What Are Cookies?

Cookies are small pieces of data stored inside the browser.

That’s it.

Cookies are not authentication by themselves.

They are just storage.

Think of cookies like a small pocket inside the browser.

Server can put data into that pocket.

Browser automatically sends it back in future requests.


How Cookies Work

When server sends response:

Set-Cookie: userId=123
Enter fullscreen mode Exit fullscreen mode

Browser stores it.

Now every future request automatically includes:

Cookie: userId=123
Enter fullscreen mode Exit fullscreen mode

That is the basic idea.


Important Thing Beginners Miss

Cookies can store:

  • Session IDs
  • JWT tokens
  • Theme settings
  • Language preferences
  • Cart information

Cookie is just a storage mechanism.

Not an authentication strategy.

this is very important 😭

many people think:

cookie == auth

NO

cookie is just storage


What Are Sessions?

Session is a server-side authentication mechanism.

This means:

Data is stored on the server.

Not inside the browser.

When user logs in:

  • Server creates a session
  • Server stores user data in memory/database
  • Server generates a unique session ID
  • Session ID is sent to browser using cookies

Example:

{
  sessionId: "abc123",
  userId: 45,
  role: "admin"
}
Enter fullscreen mode Exit fullscreen mode

Browser stores this session ID inside a cookie.

Now every request carries:

Cookie: sessionId=abc123
Enter fullscreen mode Exit fullscreen mode

Server receives it and checks:

Which user belongs to this session?
Enter fullscreen mode Exit fullscreen mode

Then server identifies the user.


Session Authentication Flow

Step 1 : Login Request

Client -> Email + Password -> Server
Enter fullscreen mode Exit fullscreen mode

Step 2 : Server Verifies User

Server checks database.

If correct:

Create Session
Enter fullscreen mode Exit fullscreen mode

Step 3 : Session Stored On Server

Example:

{
  sessionId: "abc123",
  userId: 45,
  role: "admin"
}
Enter fullscreen mode Exit fullscreen mode

Step 4 : Session ID Sent As Cookie

Set-Cookie: sessionId=abc123
Enter fullscreen mode Exit fullscreen mode

Step 5 : Browser Sends Cookie Automatically

Cookie: sessionId=abc123
Enter fullscreen mode Exit fullscreen mode

Step 6 : Server Matches Session

Server checks:

abc123 belongs to Shivam
Enter fullscreen mode Exit fullscreen mode

User authenticated.


Visual Session Flow

Login
  |
  v
Server Creates Session
  |
  v
Session Stored In Server Memory/DB
  |
  v
Session ID Sent In Cookie
  |
  v
Browser Stores Cookie
  |
  v
Every Request Sends Cookie Automatically
  |
  v
Server Verifies Session ID
Enter fullscreen mode Exit fullscreen mode

What Is JWT?

now to understand this let see the flow

user put credential and then user click on login

server receive the login detail

server verify the user (exist in his own DB)

after that server create a JWT token


now what is this JWT token ?

token is a piece of data which look like a random string but it is divided in three part

HEADER.PAYLOAD.SIGNATURE
Enter fullscreen mode Exit fullscreen mode

first random string

second user related data like

{
  userId: 45,
  role: "admin"
}
Enter fullscreen mode Exit fullscreen mode

then comes the secret key

after creating this the server send this token to the user

now the user takes this token and save this in his:

  • localStorage
  • cookie

now with each request the browser will send this token to the server in his http header

Authorization: Bearer TOKEN
Enter fullscreen mode Exit fullscreen mode

now with each req server get this token

server will put an middleware which will check the token is valid or not using the secret key we use to create this token

after this the user is given the access to the user


Visual JWT Flow

Login
  |
  v
Server Creates JWT
  |
  v
Token Sent To Browser
  |
  v
Browser Stores Token
  |
  v
Client Sends Token In Headers
  |
  v
Server Verifies JWT Signature
Enter fullscreen mode Exit fullscreen mode

Stateful Authentication

Stateful means:

Server stores user state.

Example:

Sessions

Server remembers:

Session ID -> User Data
Enter fullscreen mode Exit fullscreen mode

Every request requires checking stored session.


Stateless Authentication

Stateless means:

Server does not remember user sessions.

Example:

JWT

All information is inside token itself.

Server just verifies token.

No session lookup needed.


The Biggest Difference

Session JWT
Server stores user data Client stores complete token
Client stores only session ID Server usually stores nothing
Stateful Stateless

Then Why Did JWT Become So Popular?

Because modern applications changed.

Earlier:

Frontend + Backend = Same Server
Enter fullscreen mode Exit fullscreen mode

Traditional apps.

Like:

  • PHP websites
  • Old MVC applications
  • Monolithic apps

Sessions worked perfectly.

But modern systems became:

Frontend = React
Backend = Node.js API
Mobile App = Separate
Enter fullscreen mode Exit fullscreen mode

Now multiple clients needed authentication.

JWT became easier because:

  • mobile application use token
  • API become stateless
  • scaling becomes easier
  • microservices work better nowadays

That is why JWT exploded in popularity.


When To Use Sessions ?

Sessions are still extremely useful.

when making:

  • Traditional server-rendered apps
  • Admin dashboard
  • Banking system
  • Applications needing strict session control

Why?

Because sessions are easier to revoke.

Example:

Delete session from server
User instantly logged out
Enter fullscreen mode Exit fullscreen mode

Very controlled.


When To Use JWT

JWT works great when building:

  • APIs
  • Mobile apps
  • Distributed systems
  • Microservices
  • SPA applications like React

Because:

No session storage required
Enter fullscreen mode Exit fullscreen mode

Server scaling becomes easier.


The Hidden Problem With JWT

Many beginners think:

JWT is always better
Enter fullscreen mode Exit fullscreen mode

Not true.

JWT introduces complexity.

Especially:

  • Logout handling
  • Token expiration
  • Refresh tokens
  • Revoking compromised tokens

Once token is issued:

Server may not fully control it until expiration.

That is why many large systems still use sessions.


key and best part of session and JWT to know as developer

In Session-Based Systems

centralized control matters.

In JWT-Based Systems

scalability matters.

this line alone explain half of authentication architecture 😭


Authentication Example Using Sessions

Login Route

app.post("/login", (req, res) => {
  const sessionId = "abc123";

  sessions[sessionId] = {
    userId: 1,
    username: "shivam"
  };

  res.cookie("sessionId", sessionId);

  res.send("Logged in");
});
Enter fullscreen mode Exit fullscreen mode

Protected Route

app.get("/profile", (req, res) => {
  const sessionId = req.cookies.sessionId;

  const user = sessions[sessionId];

  if (!user) {
    return res.send("Unauthorized");
  }

  res.send(user);
});
Enter fullscreen mode Exit fullscreen mode

Authentication Example Using JWT

Login Route

const jwt = require("jsonwebtoken");

app.post("/login", (req, res) => {
  const token = jwt.sign(
    {
      userId: 1,
      username: "shivam"
    },
    "secretKey"
  );

  res.json({ token });
});
Enter fullscreen mode Exit fullscreen mode

Protected Route

app.get("/profile", (req, res) => {
  const token = req.headers.authorization.split(" ")[1];

  try {
    const decoded = jwt.verify(token, "secretKey");

    res.send(decoded);
  } catch {
    res.send("Invalid token");
  }
});
Enter fullscreen mode Exit fullscreen mode

One Common Confusion

Cookies vs Sessions

Not same.

Cookie:

Stored in browser

Session:

Stored on server

Cookie usually carries session ID.


Cookies vs JWT

Not same.

JWT is token.

Cookie is storage.

JWT can be stored inside cookies.

again 😭

cookie is just storage


Final Comparison

Thing What It Actually Is
Cookie Browser storage mechanism
Session Server-side authentication state
JWT Self-contained authentication token

Which One Should You Learn First?

Learn sessions first.

Why?

Because sessions teach the actual foundation of authentication.

Once you understand:

Server remembers user identity
Enter fullscreen mode Exit fullscreen mode

then JWT becomes much easier.

Most beginners directly jump into JWT tutorials.

Then they memorize code without understanding authentication flow.

Bad idea.

Understand the problem first.

Then understand sessions.

Then JWT.

That order builds real understanding.


Final Understanding

Authentication is basically solving one problem:

How does server remember who the user is?
Enter fullscreen mode Exit fullscreen mode

Sessions solve it by:

  • storing data on server

JWT solve it by:

  • storing data inside token

Cookies help both by:

  • storing information in browser

once u understand this

the entire authentication system starts making sense 😭


so this the end of this blog

if u liked blog then follow me i always there with new blog like this

and also like the blog

meet u in the next blog

bye bye