Understanding the JWT Structure
A JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties. A standard JWT consists of three parts separated by dots (.), looking like this: xxxxx.yyyyy.zzzzz
- Header: The first part dictates the type of the token (JWT) and the signing algorithm being used, such as HMAC SHA256 or RSA.
- Payload (Claims): The middle section contains the claims (statements about the user and additional metadata). Do not put secret information in the payload, as it is only encoded, not encrypted.
- Signature: The final part is used to verify the message wasn't changed along the way. It is generated by signing the encoded header and payload with a secure private key.
How to decode a JWT payload in JavaScript
If you are building a frontend application and need to extract the user's ID or expiration date from a JWT stored in local storage, you don't need a heavy NPM library. You can decode it natively using the browser's built-in atob() function:
function parseJwtPayload(token) {
// 1. Split the token and grab the payload (middle section)
const base64Url = token.split('.')[1];
// 2. Fix the Base64 formatting
const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
// 3. Decode the Base64 string into a JSON payload
const jsonPayload = decodeURIComponent(window.atob(base64).split('').map(function(c) {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));
// 4. Return the parsed object
return JSON.parse(jsonPayload);
}
// Usage:
// const claims = parseJwtPayload(myToken);
// console.log(claims.exp);