Fix Insecure JWT & Session Token Storage in Web Apps
Why storing auth tokens in localStorage exposes users to XSS, and how HttpOnly, Secure, SameSite cookies protect sessions.
By the end of this tutorial you will know:
- Why
localStorageis readable by any injected script (XSS) - How
HttpOnly,Secure, andSameSite=Laxcookie flags protect tokens - How to inspect JWT claims safely with our local JWT Decoder
Prerequisites: Basic understanding of HTTP cookies and authentication.
1. The big idea
localStorage is convenient, which is why so many tutorials store JWTs there. The catch is that any JavaScript running on your page—including a compromised npm package, analytics script, or XSS bug—can call localStorage.getItem("token") and steal a user's session in one line.
An HttpOnly cookie, by contrast, is invisible to document.cookie and JavaScript completely. The browser sends it automatically on requests to your backend, and scripts cannot read it.
2. The risky pattern
// Vulnerable to any XSS script on the page:
localStorage.setItem("access_token", jwt);3. The fix: HttpOnly, Secure, SameSite=Lax cookies
Set your session or refresh token from the server using Set-Cookie with all three security flags:
import { NextResponse } from "next/server";
export async function POST() {
const token = "signed-session-token";
const res = NextResponse.json({ ok: true });
res.cookies.set("session", token, {
httpOnly: true, // unreadable by JavaScript
secure: process.env.NODE_ENV === "production", // HTTPS only
sameSite: "lax", // protects against cross-site POST CSRF
path: "/",
maxAge: 60 * 60 * 24 * 7, // 7 days
});
return res;
}Inspect your session cookie in DevTools → Application → Cookies. Verify HttpOnly, Secure (in production HTTPS), and SameSite: Lax are all checked, and confirm document.cookie in the Console cannot see it.
4. Common pitfalls
| Mistake | Risk | Fix |
|---|---|---|
Storing long-lived JWTs in localStorage | Any XSS steals the token | Move session/refresh tokens to HttpOnly cookies |
Using SameSite=None without CSRF tokens | Cross-site requests send cookies | Use SameSite=Lax (or Strict) for same-site apps |
Accepting alg: "none" on the server | Forged unsigned tokens | Always enforce an explicit algorithm allowlist (HS256 / RS256) |
5. What you learned
You now know why localStorage is unsafe for session tokens and how HttpOnly, Secure, and SameSite=Lax cookies protect web authentication.