Decoding JWTs in the Frontend
You'll learn how to safely inspect JWT contents in your frontend without verifying signatures.
The Core Idea
Once you receive a JWT (perhaps from login), you often need to read what's inside—like the user's ID, roles, or when the token expires. Decoding a JWT means converting its Base64-encoded sections back into readable JSON so you can access these claims.
Important distinction: Decoding is NOT verifying. You're just reading the payload; you're not checking if the signature is valid (that's the backend's job). Think of it like reading the label on a sealed package—you can see what's written without confirming the seal is authentic.
Plain Decoding Methods
JWTs have three parts separated by dots: header.payload.signature. The payload is Base64-URL encoded, which you can decode:
function decodeJWT(token) {
const payload = token.split('.')[1]; // Get middle part
const decoded = atob(payload); // Base64 decode
return JSON.parse(decoded);
}
const token = "eyJhbGc..."; // Your JWT
const claims = decodeJWT(token);
console.log(claims.exp); // Check expiration
console.log(claims.userId); // Access custom claims
Using Libraries
Libraries like jwt-decode handle edge cases and URL-safe Base64:
import jwtDecode from 'jwt-decode';
const token = "eyJhbGc...";
const decoded = jwtDecode(token);
if (decoded.exp * 1000 < Date.now()) {
console.log("Token expired!");
}
This is purely client-side inspection—perfect for checking expiration before making requests or displaying user info from claims without hitting the server.
Key Takeaway: Decoding JWTs in the frontend lets you inspect claims like expiration and user data, but remember you're only reading the token, not validating its authenticity—never trust decoded values for security decisions without backend verification.