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

推荐订阅源

D
Docker
AI
AI
博客园 - 三生石上(FineUI控件)
腾讯CDC
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Y
Y Combinator Blog
大猫的无限游戏
大猫的无限游戏
H
Hackread – Cybersecurity News, Data Breaches, AI and More
雷峰网
雷峰网
NISL@THU
NISL@THU
S
Schneier on Security
T
Threatpost
T
Tenable Blog
Application and Cybersecurity Blog
Application and Cybersecurity Blog
IT之家
IT之家
宝玉的分享
宝玉的分享
T
Tailwind CSS Blog
C
Cybersecurity and Infrastructure Security Agency CISA
P
Privacy & Cybersecurity Law Blog
I
Intezer
Microsoft Azure Blog
Microsoft Azure Blog
月光博客
月光博客
T
Threat Research - Cisco Blogs
SecWiki News
SecWiki News
AWS News Blog
AWS News Blog
博客园 - Franky
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
P
Proofpoint News Feed
V
V2EX
Recorded Future
Recorded Future
Microsoft Security Blog
Microsoft Security Blog
S
Secure Thoughts
Google DeepMind News
Google DeepMind News
MongoDB | Blog
MongoDB | Blog
Apple Machine Learning Research
Apple Machine Learning Research
Project Zero
Project Zero
PCI Perspectives
PCI Perspectives
G
GRAHAM CLULEY
Help Net Security
Help Net Security
Cloudbric
Cloudbric
Recent Announcements
Recent Announcements
V
Visual Studio Blog
Hacker News: Ask HN
Hacker News: Ask HN
N
News and Events Feed by Topic
C
CERT Recently Published Vulnerability Notes
The Cloudflare Blog
Forbes - Security
Forbes - Security
C
Cisco Blogs
O
OpenAI News
www.infosecurity-magazine.com
www.infosecurity-magazine.com

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
Sessions vs JWT vs Cookies: Understanding Authentication Approaches
SATYA SOOTAR · 2026-05-10 · via DEV Community

Hello readers 👋, welcome to the 15th blog in our Node.js series!

In our previous posts, we built a REST API, learned how to protect routes with JWT, and explored middleware and file uploads. Authentication has come up several times, but today we’re going to take a step back and look at the bigger picture. We’ll compare three pillars of authentication in web applications: sessions, JSON Web Tokens (JWT), and cookies.

If you’ve ever been confused about when to use a session-based login, when to reach for a JWT, or where cookies fit into all this, this post will clear things up. We’ll keep it practical, avoid deep security rabbit holes, and end with a decision framework you can apply to your next project.

Let’s get started.

What are cookies?

Cookies are small pieces of data stored on the client (browser) by the server via the Set-Cookie header. They are automatically sent back to the server with every subsequent request to the same domain. That’s their superpower: they travel with every request without the client having to do anything extra.

A cookie looks something like this:

Set-Cookie: sessionId=abc123; HttpOnly; Secure; SameSite=Strict

Enter fullscreen mode Exit fullscreen mode

The browser then dutifully sends Cookie: sessionId=abc123 with each request.

Cookies alone are not an authentication method; they are a transport mechanism. They can carry a session ID, a JWT, or just a simple preference. But because sessions almost always rely on cookies, the two are often mentioned together.

Key properties you can set on cookies:

  • HttpOnly – the cookie cannot be accessed via JavaScript (document.cookie), which helps prevent XSS attacks.
  • Secure – the cookie is only sent over HTTPS.
  • SameSite – controls whether the cookie is sent on cross‑site requests, mitigating CSRF.

In a traditional session‑based authentication, the server sets a cookie containing a unique session ID, and all further requests carry that cookie to identify the user.

What are sessions?

Session‑based authentication is the classic approach. After the user logs in with valid credentials, the server creates a session – a record in a database, in‑memory store, or cache (like Redis) that contains the user’s identity and any other relevant data. The server then sends back a cookie holding only the session ID.

Every subsequent request comes with that cookie. The server reads the session ID, looks up the session data (often from a store), and knows who the user is without them sending the password again.

Let’s see a simplified Express example using express-session:

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

app.use(session({
  secret: 'your-secret-key',
  resave: false,
  saveUninitialized: true,
  cookie: { secure: true, httpOnly: true, maxAge: 3600000 } // 1 hour
}));

app.post('/login', (req, res) => {
  // authenticate user
  req.session.userId = user.id; // stored on server
  res.send('Logged in');
});

app.get('/dashboard', (req, res) => {
  if (!req.session.userId) return res.status(401).send('Unauthorized');
  // fetch user data using session.userId
  res.send(`Hello user ${req.session.userId}`);
});

Enter fullscreen mode Exit fullscreen mode

Sessions are stateful: the server must maintain a session store (memory, database, Redis). When you scale to multiple server instances, the session store must be shared, which adds complexity.

What are JWT tokens?

JSON Web Tokens (JWT) are a stateless authentication method. After a successful login, the server generates a token containing a payload (like the user’s ID and role) and signs it with a secret key. The token is sent to the client, which stores it. For each subsequent request, the client sends the token, usually in the Authorization header as a Bearer token, or sometimes in an HttpOnly cookie. The server verifies the signature, extracts the payload, and trusts that the user is who the token claims.

We’ve already implemented JWT authentication in an earlier blog. Here’s a quick recap:

const jwt = require('jsonwebtoken');

app.post('/login', (req, res) => {
  // authenticate user
  const token = jwt.sign({ userId: user.id }, 'secret', { expiresIn: '1h' });
  res.json({ token });
});

app.get('/profile', (req, res) => {
  const token = req.headers.authorization?.split(' ')[1];
  if (!token) return res.status(401).send('No token');
  try {
    const decoded = jwt.verify(token, 'secret');
    req.user = decoded;
    res.send(`Profile of user ${req.user.userId}`);
  } catch (err) {
    res.status(403).send('Invalid token');
  }
});

Enter fullscreen mode Exit fullscreen mode

Because JWT contains all the info needed (in the payload), the server doesn’t need to look up a session. That’s the stateless magic.

Stateful vs stateless authentication

This is the key distinction.

  • Stateful (sessions): The server keeps track of authenticated users. Each request requires a session lookup. This works great for traditional multi‑page apps because scaling requires a shared session store. Logout is easy: just destroy the session on the server.
  • Stateless (JWT): The server doesn’t store anything. It trusts the token after verifying the signature. This makes horizontal scaling a breeze. Logout is trickier: since the server doesn’t remember the token, you can’t invalidate it without a blacklist (bringing back some state). Usually, you set short expiration and rely on the client removing the token.

Think of sessions as a coat-check ticket: you give the clerk your coat, get a ticket, and later hand the ticket back to retrieve your coat. The clerk (server) remembers you. JWT is like a digital passport: the passport says who you are, and the border official (server) verifies its authenticity without calling home. Both have their place.

Sessions vs JWT: detailed comparison

Feature Session‑based JWT
State Stateful (server stores session data) Stateless (server only verifies token)
Storage Session ID stored in a cookie; session data stored server‑side (memory, DB, Redis) Token stored client‑side: browser (localStorage, sessionStorage) or HttpOnly cookie; no server‑side storage
Scalability Requires shared session store across instances (e.g., Redis) Easy to scale horizontally; no server‑side data sharing needed
Logout Server deletes session – immediate effect No server‑side record; token can’t be invalidated instantly unless a blacklist is used. Short expiry & client removal are typical
Security typical risks Session hijacking (if cookie stolen), CSRF (mitigated with SameSite, tokens) Token theft (if stored in non‑HttpOnly cookie or localStorage), XSS (if accessible via JS), token size
Payload visibility Server‑side, opaque to client Payload is Base64‑encoded (not encrypted); everyone can read it, but signature ensures integrity. Never put secrets in payload
Typical use case Traditional server‑rendered web apps, multi‑page apps, apps with centralized user management APIs, single‑page applications (SPAs), mobile apps, microservices, third‑party integrations

Note that you can store a JWT inside an HttpOnly cookie, blending some benefits: you get automatic cookie sending (no need to attach header manually) and protection from XSS, while still being stateless. The choice of where to store the token is separate from the choice of session vs JWT.

When to use each method

Use sessions when:

  • You have a traditional server‑rendered application (EJS, Pug, etc.).
  • You need fine‑grained control over active session invalidation (e.g., force logout, revoke access instantly).
  • You’re comfortable managing a session store (or don’t mind the overhead for a simple app).
  • You want to keep sensitive data on the server.

Use JWT when:

  • You are building a REST API that serves multiple frontends (web, mobile, desktop).
  • You want to scale horizontally without worrying about a shared data store.
  • You need to pass authorization across multiple independent services (microservices).
  • Your client is a SPA where the frontend handles presentation and stores the token (e.g., in memory or localStorage, though HttpOnly cookie is safer).

A hybrid approach: store a short‑lived JWT inside an HttpOnly, Secure, SameSite cookie. That way you get automatic cookie handling, XSS protection, and still remain stateless on the server. This is increasingly popular in modern frameworks.

Conclusion

Sessions, cookies, and JWT aren’t mutually exclusive; they’re pieces of the authentication puzzle. Cookies transport data (session IDs or JWTs) seamlessly. Sessions give you server‑side control at the cost of state. JWT gives you stateless scalability at the cost of instant invalidation. Choosing between them depends on your application architecture, scalability needs, and security priorities.

To recap:

  • Cookies are a transport mechanism, automatically sent with every request, and can be secured with HttpOnly, Secure, and SameSite flags.
  • Sessions store user state on the server and use a cookie holding a session ID. They are stateful and great for traditional web apps.
  • JWT embeds user information in a signed token; the server doesn’t need a lookup. They are stateless and ideal for APIs, SPAs, and microservices.
  • The decision often hinges on stateful vs stateless needs and where you want to store sensitive data.

In the next post, we’ll start connecting Express to databases; building a full‑stack authentication flow with registration and login that persists real data. See you then!


Hope you found this helpful! If you spot any mistakes or have suggestions, let me know. You can find me on LinkedIn and X, where I post more about web development.