How to Decode JWTs Securely on the Client-Side
JSON Web Tokens (JWT) are the standard for transmitting secure claims between parties. If you're building a modern React or Next.js application, chances are you'll need to parse a JWT to extract user information like their ID, email, or role.
In this guide, we'll explore how JWTs work and how to securely decode them on the client-side.
What is a JWT?
A JWT consists of three parts separated by dots (.):
Contains metadata about the type of token and the cryptographic algorithms used to secure its contents.
Contains the claims (the actual data, like userId).
Used to verify that the sender of the JWT is who it says it is and to ensure that the message wasn't changed along the way.
Decoding vs. Verifying
It is critical to understand the difference between decoding and verifying:
- Decoding is just reading the base64-encoded string. It does not guarantee the token is authentic.
- Verifying uses a secret key to ensure the token was generated by your server and hasn't been tampered with.
Security Warning
You should never trust the payload of a JWT for authorization on the frontend without verifying it on your backend first.
How to Decode a JWT in JavaScript
Since the payload is just a Base64Url encoded string, you don't actually need a heavy cryptographic library to read it. You can parse it using built-in browser APIs like atob.
function decodeJwt(token) {
try {
const base64Url = token.split('.')[1];
const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
const jsonPayload = decodeURIComponent(
window.atob(base64)
.split('')
.map((c) => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2))
.join('')
);
return JSON.parse(jsonPayload);
} catch (error) {
console.error("Invalid token format");
return null;
}
}The Easier Way
If you don't want to write and maintain your own parsing utility, you can use the wildly popular jwt-decode library from NPM:
npm install jwt-decodeimport { jwtDecode } from "jwt-decode";
const token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...";
const decoded = jwtDecode(token);
console.log(decoded.userId);Try it out yourself!
If you just have a token and want to see what's inside it without writing any code, you can use our free online tool.
Decode your JWT securely hereAll processing happens entirely locally in your browser, so your tokens are never sent to our servers.