Skip to main content

Command Palette

Search for a command to run...

Sessions vs JWT vs Cookies: Understanding Authentication Approaches

Updated
β€’3 min read
  1. What sessions are => A session is a way for the server to remember a user.

    How it works:

    1. User logs in

    2. Server creates a session (stores user data on server)

    3. Server sends a session ID to the browser

    4. Browser sends that session ID with every request

    5. Server checks it and recognizes the user

    πŸ‘‰ Think of it like a cloakroom token:

    • Your data is stored safely (on server)

    • You just carry a small token (session ID)

  2. What cookies are => A cookie is a small piece of data stored in the browser.

    Key points:

    • Sent automatically with every request

    • Can store things like:

      • Session ID

      • Preferences

      • Login info (not sensitive data ideally)

    πŸ‘‰ Important:
    Cookies are just storage, not authentication itself.

  3. What JWT tokens are => JWT = JSON Web Token

    It’s a self-contained token that stores user information.

    Structure:

    • Header

    • Payload (user data)

    • Signature (security)

    How it works:

    1. User logs in

    2. Server creates a JWT

    3. Sends it to client

    4. Client stores it (usually in localStorage or cookie)

    5. Client sends JWT with every request

    6. Server verifies it (no DB lookup needed)

    πŸ‘‰ Think of JWT like a digital ID card you carry yourself.

  4. Stateful vs stateless authentication => 🧠 Stateful (Sessions)

    • Server stores user data

    • Needs memory/database

    • Tracks each user session

    ⚑ Stateless (JWT)

    • Server stores nothing

    • All info is inside token

    • Faster and scalable

  5. Differences between session-based auth and JWT =>

    Feature Session-Based Auth 🧠 JWT-Based Auth ⚑
    Storage Server Client
    State Stateful Stateless
    Speed Slower (DB lookup) Faster
    Scalability Harder Easier
    Security Very secure (server-side) Depends on storage
    Token Size Small (just ID) Larger (data included)
    Logout Handling Easy Hard (token still valid)
    Use in APIs Not ideal Very popular
  6. When to use each method =>

    βœ… Use Sessions When:

    • You are building a traditional website

    • You need strong control over users

    • You want easy logout handling

    • Example:

      • Banking apps

      • Admin dashboards

    βœ… Use JWT When:

    • You are building APIs or mobile apps

    • You need scalability

    • You have microservices architecture

    • Example:

      • REST APIs

      • Mobile backend

      • Single Page Apps (React, Angular).