Skip to content

Instantly share code, notes, and snippets.

@thebearingedge
Created April 28, 2022 04:44
Show Gist options
  • Save thebearingedge/1b9a9dfbc41b6a614869b45b87dafc78 to your computer and use it in GitHub Desktop.
Save thebearingedge/1b9a9dfbc41b6a614869b45b87dafc78 to your computer and use it in GitHub Desktop.
Decode a JSON Web Token in the browser.
function decode(token) {
const [, payload] = token.split('.')
try { return JSON.parse(atob(payload)) } catch (err) {}
const unsafe = payload.replace(/-/g, '+').replace(/_/g, '/')
let padded = unsafe + '='.repeat(4 - unsafe.length % 4)
const uriComponent = atob(padded).replace(/(.)/g, (_, c) => {
const hex = c.charCodeAt(0).toString(16).toUpperCase()
return '%' + (hex.length < 2 ? '0' : '') + hex
})
return JSON.parse(decodeURIComponent(uriComponent))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment