This flew over my head since 2022 โ you and every dev before their JWT awakening.
You're not alone if you've ever felt confused about JWTs (JSON Web Tokens). But today, letโs break it down in plain English, with enough sauce to make it stick.
๐ What the Heck is JWT?
JWT = a secure way to send user data from server โ client.
But not just any data โ usually:
{
"id": "user_id_123",
"email": "david@email.com",
"role": "admin"
}
The server takes this, signs it, and sends it back to the frontend as a token. That token is your magic key to access protected routes.
๐ JWT Flow in the Real World
Hereโs the flow that makes you look like a senior dev:
- User logs in โ Server sends a JWT back.
- Frontend stores the token (usually in localStorage or a secure cookie).
- On every request, frontend sends it back to the server via the Authorization header.
- Backend checks it, confirms itโs not tampered with, and knows whoโs talking.
๐ง What Does the Frontend Do With It?
๐ฅ This is where your aha moment lives.
JWT on the frontend = no need to persist user manually.
Instead of saving user data in Zustand or Redux, just:
Store the token in localStorage.
Decode it when needed to get stuff like userId, email, etc.
npm install jwt-decode
import jwtDecode from "jwt-decode";
const token = localStorage.getItem("token");
if (token) {
const decoded = jwtDecode(token);
console.log(decoded.id); // user ID from token payload
}
Yes โ itโs that simple. You donโt even verify it on the frontend (thatโs backendโs job).
โ ๏ธ Zustand vs JWT โ Who Wins?
Zustand is ๐ฅ for managing state in the moment, but it doesnโt persist user sessions on its own.
Instead:
Use JWT to persist auth state
Optionally: Decode and drop relevant info into Zustand for quick access.
๐ก TL;DR
- JWT = user's data + secret sauce (signature)
- Sent from backend โ stored on frontend
- Frontend decodes it to know the logged-in user
- No need to save full user info manually
- Send it back to the server with every request as proof of identity
๐ BONUS: Pro Tips
- Donโt trust the token blindly โ always verify on the backend.
- Donโt store sensitive info inside (like passwords).
- Use httpOnly cookies instead of localStorage if you're paranoid about security.
- Use jwt-decode on the frontend โ donโt try to decode manually, your brain deserves better.
๐ Final Words
JWT is not magic. Itโs just a clever way to carry a userโs identity like a digital passport. Once you get the hang of it, everything else about authentication starts to click.
Now go flex that knowledge in your code โ or better yet, drop it on X like:
โI just decode the JWT on load and store the userโs ID in Zustand โ keeps it clean.โ
Boom! Instant clout!
Top comments (0)