惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

酷 壳 – CoolShell
酷 壳 – CoolShell
aimingoo的专栏
aimingoo的专栏
Microsoft Security Blog
Microsoft Security Blog
NISL@THU
NISL@THU
T
Threatpost
T
The Exploit Database - CXSecurity.com
T
Threat Research - Cisco Blogs
S
Securelist
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
人人都是产品经理
人人都是产品经理
B
Blog RSS Feed
S
Secure Thoughts
MyScale Blog
MyScale Blog
O
OpenAI News
P
Palo Alto Networks Blog
美团技术团队
C
Cyber Attacks, Cyber Crime and Cyber Security
TaoSecurity Blog
TaoSecurity Blog
量子位
L
Lohrmann on Cybersecurity
G
GRAHAM CLULEY
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
T
Tailwind CSS Blog
Know Your Adversary
Know Your Adversary
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Simon Willison's Weblog
Simon Willison's Weblog
宝玉的分享
宝玉的分享
PCI Perspectives
PCI Perspectives
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
C
Cybersecurity and Infrastructure Security Agency CISA
T
Tenable Blog
I
InfoQ
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Microsoft Azure Blog
Microsoft Azure Blog
Recent Announcements
Recent Announcements
S
Security @ Cisco Blogs
S
Schneier on Security
B
Blog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
The Cloudflare Blog
AWS News Blog
AWS News Blog
IT之家
IT之家
V
Vulnerabilities – Threatpost
The Hacker News
The Hacker News
H
Heimdal Security Blog
I
Intezer
A
Arctic Wolf
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
H
Help Net Security
W
WeLiveSecurity

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Session VS Cookie Vs JWT
Shivam Yadav · 2026-05-08 · via DEV Community

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