AyushShah
Back to Blog
Stop Using JWT in localStorage — Here's Why (and What to Do Instead)
Web DevelopmentTechnologySecurityLifestyleBest Practices

Stop Using JWT in localStorage — Here's Why (and What to Do Instead)

By AyushMay 18, 2025
48 views

Stop Using JWT in localStorage — Here's Why (and What to Do Instead)

You might've heard developers say: "Store the JWT token in localStorage or sessionStorage, easy peasy." Sounds convenient, right? But here's the harsh truth — Storing tokens in localStorage can ruin your app's security.

What's the Problem?

Anyone can read your localStorage. Let's say you store your login token like this: localStorage.setItem("token", "your-secret-jwt-token") Any JavaScript running on the page (even a random library you installed) can do: localStorage.getItem("token") Boom. They have your token. No permission needed. No pop-up warning. Nothing.

But What If It's a Malicious Library?

Exactly. You might use a third-party package. It might have been compromised. And inside its code… this one evil line: const token = localStorage.getItem("token") sendToHackerServer(token) You'd never know. No alerts. No logs. Just stolen sessions.

The XSS Nightmare

Even worse — in a Cross-Site Scripting (XSS) attack, an attacker can inject their own JavaScript into your site. And the first thing their script will do? const token = localStorage.getItem("token") Yep. They'll steal it and impersonate your user.

What Happens Next?

  • Log in as you
  • Change your profile
  • Delete your account
  • Wreak absolute havoc

The Fix? HttpOnly Cookies

Instead of localStorage, send tokens using HttpOnly Cookies: Set-Cookie: token=your-jwt; HttpOnly; Secure; SameSite=Strict This cookie will: • Be automatically included in requests • Not be accessible via JavaScript • Be much harder to steal via XSS

Comparison Time

MethodSecure from XSSAccessible via JSBest for
localStorage❌ No✅ YesQuick hacks (not safe)
HttpOnly Cookie✅ Yes❌ NoReal-world secure apps

TL;DR — Don't Be That Dev

  • 🚫 Stop storing JWTs in localStorage
  • ✅ Use HttpOnly cookies
  • 🔐 Secure your users, your app, and your future
Tags:
Web DevelopmentTechnologySecurityLifestyleBest Practices