Decode a JWT
Medium · Auth
A JWT looks like header.payload.signature, where header and payload are JSON encoded as base64url. Write decodeJwt(token) that returns { header, payload }, or null if the token is malformed.
This only DECODES the token. It does not verify the signature, so never trust the result for auth decisions; a real server uses a library like jsonwebtoken to verify it.
To decode a part:
1. base64url → base64: replace - with + and _ with /, then add = until the length is a multiple of 4.
2. atob gives a binary string; turn it into bytes and decode them with TextDecoder (so UTF-8 text like "გიორგი" works).
3. JSON.parse it.
Return null if there are not exactly 3 parts, the header or payload part is empty, decoding/parsing fails, or header/payload is not a plain object (arrays and strings are not allowed). The signature part may be empty.
Next: Parse a Raw HTTP Request