🔐 Knowledge for the Day: Is storing JWT Token in localStorage Safe? 🤔 Most Developers Get This Wrong!

When we build login + token-based systems in frontend (React / Angular / Vue), 99% of developers use:

localStorage.setItem("token", jwtToken);        

But wait... Is that secure enough?

Let's break it down 👇


🧨 Problem with localStorage?

→ It's vulnerable to XSS (Cross Site Scripting) attacks.

If attacker injects JS somehow:

console.log(localStorage.getItem("token"))        

Boom! Your user session is gone.


🛡️ What is Recommended?

Article content

Ideal Flow for Secure Apps (Spring Security + JWT)

  1. User Login
  2. Backend sends Token in HTTPOnly Cookie
  3. Browser auto attaches Token in API calls
  4. Java Backend reads token from Cookie safely.


Java Backend Example to Send HTTPOnly Cookie:

ResponseCookie cookie = ResponseCookie.from("token", jwt)
        .httpOnly(true)
        .secure(true)
        .path("/")
        .maxAge(Duration.ofHours(1))
        .build();

response.setHeader(HttpHeaders.SET_COOKIE, cookie.toString());        

Final Thought 💡

localStorage → Easy but risky HTTPOnly Cookie → Extra Safe & Professional

Choose based on your app's sensitivity!


Ideal Flow for Secure Apps (Spring Security + JWT)

1. User Login → Send Credentials

POST /login
{
  "username": "john",
  "password": "pass123"
}        

2. Backend Generates JWT → Store in HTTPOnly Cookie

ResponseCookie cookie = ResponseCookie.from("jwt", token)
        .httpOnly(true)
        .secure(true)
        .path("/")
        .maxAge(Duration.ofHours(1))
        .build();

response.setHeader(HttpHeaders.SET_COOKIE, cookie.toString());        

3. Frontend → No Need to Manually Store Token Anywhere!

Browser automatically sends the cookie in every request.

Example Request from Browser:

GET /profile
Cookie: jwt=eyJhbGciOiJIUzI1NiIsInR...        

4. Backend Validates Token (Spring Security Filter)

String token = getTokenFromCookie(request);

if (validate(token)) {
   Allow Access
} else {
   Reject
}        

💡 Final Takeaway for Developers:

  • → localStorage = Easy but risky
  • → InMemory = Safer but temporary
  • → HTTPOnly Cookie = Best for secure & production-grade apps


🔥 Bonus Tip:

If your API is fully stateless & public — Bearer Token in header is fine.

If your API is sensitive → Always prefer HTTPOnly Cookie.


Stay tuned for more developer-friendly deep-dives!

To view or add a comment, sign in

More articles by Alpesh Makwana

Insights from the community

Others also viewed

Explore topics