How can I decode the payload of JWT using JavaScript? Without a library. So the token just returns a payload object that can consumed by my front-end app.
Example token: xxxxxxxxx.XXXXXXXX.xxxxxxxx
And the result is the payload:
{exp: 10012016 name: john doe, scope:['admin']}
Each JWT contains a payload. The payload is a base64 encoded JSON object that sits between the two periods in the token. We can decode this payload by using atob() to decode the payload to a JSON string and use JSON. parse() to parse the string into an object.
Working unicode text JWT parser function:
function parseJwt (token) { var base64Url = token.split('.')[1]; var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/'); var jsonPayload = decodeURIComponent(atob(base64).split('').map(function(c) { return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2); }).join('')); return JSON.parse(jsonPayload); };
Simple function with try - catch
const parseJwt = (token) => { try { return JSON.parse(atob(token.split('.')[1])); } catch (e) { return null; } };
Thanks!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With