base64
atob 'not correctly encoded': base64url, padding, and the fix
Why atob() throws InvalidCharacterError on JWTs, bad padding and data URLs, what each browser's message says, and how to decode base64url and UTF-8 text correctly.
By Kyle Hurst ·
Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded almost never means the data is corrupt. atob accepts exactly one alphabet (A–Z a–z 0–9 + /), ASCII whitespace, and up to two = at the very end. Anything else fails, and the most common “anything else” is base64url, the variant every JWT uses. If your string came from a JWT, swap - for + and _ for / and it will decode. The rest of this post covers the other six causes, the garbled text you get once the error is gone, and three fixes we tested.
Every result below comes from running atob in Node 22.18.0 (re-checked in Node 26.13.1, same results). Browser wordings are quoted from browser source code, cited inline, because we did not run a browser for this post.
The same error in four runtimes
| Runtime | What you see | Source |
|---|---|---|
| Chrome, Edge | InvalidCharacterError: Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded. | Chromium’s atob-btoa test expectations |
| Chrome, chars above U+00FF | ...The string to be decoded contains characters outside of the Latin1 range. | Same file |
| Firefox | InvalidCharacterError: String contains an invalid character | Gecko domerr.msg, nsContentUtils::Atob |
| Safari | InvalidCharacterError: The string contains invalid characters. | WebKit WindowOrWorkerGlobalScope.cpp, DOMException.cpp |
| Node | Invalid character, or The string to be decoded is not correctly encoded. | Run on this machine |
All of them throw a DOMException named InvalidCharacterError, because that is what the HTML spec requires. Firefox and Safari use one message for every failure. Firefox’s wording is misleading enough that Mozilla bug 1627511 exists for it: atob("+") reports an “invalid character” when every character is valid and the real problem is the length. That bug is still open. Node splits the two cases: Invalid character for a bad character or a misplaced =, and not correctly encoded when the length is wrong.
What atob actually checks
The HTML spec defines atob as three steps: run forgiving-base64 decode, throw InvalidCharacterError on failure, return the result. The forgiving decoder in the WHATWG Infra standard begins like this:
- Remove all ASCII whitespace (tab, line feed, form feed, carriage return, space).
- If the length is now a multiple of 4 and the string ends with one or two
=, remove them. - If the length divided by 4 leaves a remainder of 1, fail.
- If any character is not
+,/or an ASCII letter or digit, fail.
The remaining steps turn every four characters into three bytes and decode a short final group without complaint. Every case below traces back to one of those four steps.
Seven causes, with real output
| Input | Result in Node 22 | Spec step |
|---|---|---|
JWT segment containing _ | Invalid character | 4 |
YQ (length 2), YWI (length 3) | "a", "ab" | 3 passes |
Y, YWJjZ (length mod 4 = 1) | The string to be decoded is not correctly encoded. | 3 |
SGVs bG8g\nV29y\tbGQh | "Hello World!" | 1 strips it |
SGVs + non-breaking space + bG8= | Invalid character | 4 |
YQ= (one = on a 3-char string) | Invalid character | 2 skipped, then 4 |
YQ===, SG=VsbG8=, YQ==YQ== | Invalid character | 4 |
data:text/plain;base64,SGVsbG8= | Invalid character | 4 |
YQ%3D%3D | Invalid character | 4 |
SGVsbG8é, “SGVsbG8=” | Invalid character | 4 |
atob(undefined) | not correctly encoded | 3 ("undefined" is 9 chars) |
atob(null) | returns "ée" | none, it “worked” |
1. base64url (JWTs, URL-safe tokens)
RFC 4648 §5 defines base64url: the same encoding, with - and _ in place of + and /. JWTs use it and also drop the padding. The alphabet differences are covered in base64 vs base32 vs base58. Here is the payload segment of a token we built with {"sub":"user_7","name":"Zoë Ångström","iat":1763510400}:
atob('eyJzdWIiOiJ1c2VyXzciLCJuYW1lIjoiWm_DqyDDhW5nc3Ryw7ZtIiwiaWF0IjoxNzYzNTEwNDAwfQ')
// InvalidCharacterError: Invalid character
The single _ (from the UTF-8 bytes of ë) is enough. A JWT payload that happens to contain neither - nor _ decodes fine, which is why this bug appears only for some users or some tokens.
2. Missing padding
Lengths 2 and 3 (mod 4) decode, because the spec never requires the =. Length 1 always fails, since one character carries only 6 bits and cannot make a byte. A correctly encoded string never ends up with a length of 1 mod 4. If yours does, a character was lost or added.
3. Whitespace and line breaks
Base64 wrapped across lines, as in PEM files and email attachments, decodes fine: step 1 removes spaces, tabs and both styles of line break. Only those five characters are removed. A non-breaking space (U+00A0, common after copying from a web page or a chat app) and a vertical tab both fail with Invalid character.
4. Misplaced or extra =
Padding is removed only when it sits at the end of a string whose length is a multiple of 4, and only one or two of it. So YQ== works, YQ= fails, YQ=== fails, and an = in the middle fails. The = in the middle usually comes from concatenating two padded strings (YQ==YQ==). Decode each piece and join the bytes instead. One quirk runs the other way: atob('YR==') returns "a", the same as YQ==, because the spec discards the leftover bits without checking that they are zero. Two different strings can decode to the same bytes, so never compare base64 text to decide whether two values are equal.
5. A data: URL prefix
data:image/png;base64, contains :, ; and ,, none of which are in the alphabet. Cut everything up to and including the first comma: atob(url.slice(url.indexOf(',') + 1)). Or let the platform do it. The Fetch spec’s data: URL processor percent-decodes the body and then runs the same forgiving-base64 decode, so await (await fetch(dataUrl)).arrayBuffer() gives you bytes directly. In Node 22, fetch('data:text/plain;base64,SGV%73bG8%3D') returned "Hello".
6. URL encoding, and + turned into a space
If the string went through a URL, %2B and %3D stand in for + and =, and atob rejects the %. Run decodeURIComponent first. The nastier variant throws nothing. Form decoding turns + into a space (see URL encoding explained for why), and atob then silently strips the space:
const token = btoa('Hi>>?>'); // "SGk+Pj8+"
const got = new URLSearchParams('t=' + token).get('t'); // "SGk Pj8 "
atob(got); // "Hi\u000f\u008f" (wrong, no error)
The length dropped from 8 to 6, which is legal, so you get wrong bytes and no exception. The fix is on the sending side: encodeURIComponent(token) gives SGk%2BPj8%2B, which survives, or send base64url and avoid + entirely. Our URL encoder shows what a given string turns into.
7. Non-ASCII and non-strings
Accented letters, curly quotes from a word processor, and emoji are not in the alphabet. Chrome reports characters above U+00FF with its separate “outside of the Latin1 range” message. The argument is also converted to a string first, so atob(undefined) decodes the text "undefined" (9 characters, so it fails step 3), and atob(null) decodes "null" into "ée" with no error. Chromium’s own test expects the same results (atob(null) returns ée, atob(undefined) throws). If you see ée in your output, a variable was null.
The error is gone and the name is garbled
Fix the alphabet, and the token from cause 1 decodes. It just doesn’t look right:
atob(b64)
// '{"sub":"user_7","name":"Zoë Ãngström","iat":1763510400}'
atob returns what MDN calls a “binary string”. The HTML spec describes it as “a string consisting of characters in the range U+0000 to U+00FF, each representing a binary byte”. ë is two UTF-8 bytes, C3 AB, so it comes back as two characters, ë. Å is C3 85, and U+0085 is an invisible control character, so you see à and the next letter. That pattern is classic mojibake, explained in why text shows Ã. JSON.parse accepts it, and the bad name reaches your UI.
The fix is to treat the result as bytes and decode them as UTF-8:
function b64urlToB64(s) {
s = s.replace(/-/g, '+').replace(/_/g, '/');
return s + '='.repeat((4 - (s.length % 4)) % 4);
}
function decodeJwtPart(part) {
const bytes = Uint8Array.from(atob(b64urlToB64(part)), (c) => c.charCodeAt(0));
return JSON.parse(new TextDecoder().decode(bytes));
}
decodeJwtPart(b64).name // 'Zoë Ångström'
The re-padding line is optional for atob, which accepts unpadded input, but it keeps the string valid for stricter decoders. You will also see the older decodeURIComponent(escape(atob(s))) idiom. It works for UTF-8 text, but escape is a legacy function, and on bytes that are not valid UTF-8 it throws URIError: URI malformed. TextDecoder substitutes U+FFFD instead. For the header and payload fields themselves, see how JWTs work.
Three fixes, tested
1. Replace, re-pad, atob, TextDecoder. The snippet above works in every browser and every Node version that has atob.
2. Node: Buffer.from(s, 'base64url'). In Node 22.18 it decoded our segment to the correct Zoë Ångström with .toString('utf8'). The Node Buffer docs say 'base64url' “will also correctly accept regular base64-encoded strings”, and that 'base64' also accepts the URL-safe alphabet and ignores whitespace. Buffer is much more lenient than atob, too lenient for validation: Buffer.from('SGVsbG8!!!', 'base64') returned Hello with no error.
3. Uint8Array.fromBase64 and toBase64. These are built in now:
const bytes = Uint8Array.fromBase64(part, { alphabet: 'base64url' });
new TextDecoder().decode(bytes); // '{"sub":"user_7","name":"Zoë Ångström",...}'
new TextEncoder().encode('José 🚀').toBase64({ alphabet: 'base64url', omitPadding: true })
// 'Sm9zw6kg8J-agA'
MDN marks fromBase64 as Baseline 2025, newly available since September 2025. caniuse lists Chrome and Edge 140, Firefox 133, and Safari 18.2 as the first supporting versions (88.87% global usage when we checked on 2026-11-19). It is not in Node 22.18 or Node 24.22.1 (typeof Uint8Array.fromBase64 is 'undefined'). MDN’s compatibility data lists Node 25.0.0 as the first version with it, and Node 26.13.1 has it. The errors are clearer than atob’s, and they are SyntaxErrors rather than DOMExceptions:
fromBase64(jwtPart) SyntaxError: Found a character that cannot be part of a valid base64 string.
fromBase64('Y') SyntaxError: The base64 input terminates with a single character, excluding padding (=).
fromBase64('YR==', {lastChunkHandling: 'strict'})
SyntaxError: The base64 input terminates with non-zero padding bits.
The default alphabet is still standard base64, so forgetting { alphabet: 'base64url' } reproduces the original bug. Whitespace is ignored, as with atob. Use lastChunkHandling: 'strict' when you need to reject non-canonical input. Feature-detect before relying on it.
btoa: “characters outside of the Latin1 range”
The reverse error has one cause. btoa reads each character as one byte, so anything above U+00FF throws. Chromium’s message is Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range. Firefox and Safari reuse the same messages as for atob above. Node 22 says Invalid character. MDN calls this a “Character Out Of Range” exception. A trap sits just below the limit: btoa('José') does not throw, because é is U+00E9. It encodes é as the single Latin-1 byte E9 (Sm9z6Q==), which a UTF-8 decoder on the other end will not read as é. Encode to UTF-8 first:
btoa(String.fromCodePoint(...new TextEncoder().encode('José 🚀'))) // 'Sm9zw6kg8J+agA=='
MDN’s btoa page (“Unicode strings”) and web.dev’s The nuances of base64 encoding strings in JavaScript cover this in depth, including what happens to lone surrogates. We won’t repeat them.
What our tools do with these inputs
All three run in your browser. Nothing you paste is uploaded.
Base64 Encode / Decode accepts standard base64 and base64url without a mode switch, and decodes the bytes with TextDecoder in strict mode. Our JWT payload segment decodes to the correct Zoë Ångström JSON, with a note that the input was URL-safe base64. Line-wrapped input, missing padding and YQ= all decode. A data:text/plain;base64, prefix is removed and the part after the comma is decoded, with a note saying so. The other inputs from the table get a specific message instead of a generic one: Y reports a length that is “one more than a multiple of 4”, YQ==YQ== reports "=" at position 3 as padding in the middle of the string, the non-breaking-space string reports “Non-breaking space (U+00A0) at position 5”, and YQ%3D%3D is reported as URL-encoded, with a pointer to the URL decoder. Like atob, it does not check the leftover bits, so YR== still decodes to a. Valid base64 of binary data is not called invalid: iVBORw0KGgo= reports that the input is valid base64 but the 8 decoded bytes are not UTF-8 text, shows them as 89 50 4E 47 0D 0A 1A 0A, names a PNG image, and links to the image tool. Encoding goes through UTF-8, so btoa’s Latin-1 error doesn’t appear, and you can choose padded standard output (José 🚀 gives Sm9zw6kg8J+agA==) or URL-safe output without padding (Sm9zw6kg8J-agA).
JWT Decoder handles base64url. It swaps - and _ for + and /, restores the padding, and decodes the bytes as UTF-8, so our Zoë Ångström token shows the right name (we ran its parsing function on that token in Node to confirm). Errors name the part that failed, for example Invalid JWT: Payload is not valid base64url. Expected format: header.payload.signature, or Expected 3 dot-separated parts, got 2. for a token with a part missing. It does not verify signatures.
Base64 ↔ Image doesn’t call atob. It hands the string to the browser as a data URL, adding data:image/png;base64, if you pasted bare base64. Per the Fetch spec, the browser then percent-decodes the body and runs the same forgiving decode. A full data URL or URL-encoded %3D padding should therefore load, while base64url still fails with “Invalid base64 image data”.
If you are holding a token right now: paste it into the JWT decoder. If it’s plain base64, swap -_ for +/, strip any data: prefix or % escapes, and decode with TextDecoder rather than reading atob’s output as text.