Skip to main content

JavaScript function to decode a JWT payload.

/**
 * Decode a JWT payload
 *
 * https://stackoverflow.com/a/38552302
 * https://vanillajstoolkit.com/helpers/parsejwt/
 *
 * @param  {String} token The JWT
 * @return {Object}       The decoded payload
 */
function parseJWT(token) {
    let base64Url = token.split(".")[1];
    let base64 = base64Url.replace(/-/g, "+").replace(/_/g, "/");

    let jsonPayload = decodeURIComponent(
        atob(base64)
            .split("")
            .map(function (c) {
                return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2);
            })
            .join("")
    );

    return JSON.parse(jsonPayload);
}