When building authentication in a MERN application, one of the most common questions is:
Where should I store my JWT token?
Most developers end up choosing between:
- Local Storage
- HTTP-only Cookies
Both work — but they come with very different security trade-offs.
This post breaks down when to use what, and why it matters in real-world apps.
What is a JWT (quick recap)
A JSON Web Token (JWT) is commonly used to:
- Authenticate users
- Maintain sessions in stateless APIs
- Secure routes between frontend and backend
The real question isn’t whether to use JWT — it’s where to store it safely.
Option 1: Storing JWT in Local Storage
Why developers like it
- Very easy to implement
- Simple to access in frontend code
- Works well for quick prototypes
localStorage.setItem("token", jwtToken);
The problem
Tokens stored in Local Storage are accessible via JavaScript.
That means:
- If your app has an XSS vulnerability
- An attacker can read the token
- And impersonate the user
Summary
Pros
- Simple
- Fast to implement
Cons
- Vulnerable to XSS
- Not recommended for sensitive production apps
Option 2: Storing JWT in HTTP-only Cookies
Why professionals prefer it
HTTP-only cookies cannot be accessed via JavaScript.
res.cookie("token", jwtToken, {
httpOnly: true,
secure: true,
sameSite: "strict"
});
Benefits
- Protects against XSS attacks
- Browser automatically sends cookies with requests
- Widely used in production systems
The trade-off
Cookies can be vulnerable to CSRF attacks, which means:
- You must use
sameSite - Or implement CSRF tokens
Summary
Pros
- Safer against XSS
- Production-ready
Cons
- Slightly more setup
- Requires CSRF awareness
Security Comparison
| Concern | Local Storage | HTTP-only Cookies |
|---|---|---|
| XSS Protection | ❌ No | ✅ Yes |
| CSRF Risk | ✅ Low | ❌ Needs handling |
| JS Access | ✅ Yes | ❌ No |
| Production Use | ⚠️ Limited | ✅ Recommended |
What do real-world apps use?
- Side projects / demos → Local Storage is acceptable
- Production apps → HTTP-only Cookies + CSRF protection
- FinTech / SaaS → Cookies almost always
Security-sensitive apps prioritize risk reduction over convenience.
Interview-ready answer (save this)
“I prefer HTTP-only cookies for JWT storage because they protect against XSS. I handle CSRF using sameSite or CSRF tokens.”
Simple, honest, and realistic.
Final Thoughts
There’s no “one-size-fits-all” solution — but for production MERN apps, HTTP-only cookies are usually the safer choice.
If you’re just starting out, Local Storage helps you learn faster.
If users and data matter, cookies are worth the effort.
Let’s discuss
How do you store JWTs in your apps — and why?
#mern #jwt #authentication #websecurity #nodejs #react
Top comments (0)