Base64 Encoding a Unicode Name in Python 3.11, Node 22 and the Browser: Why btoa() Threw InvalidCharacterError on My Username
Last week I built a tiny email-verification link for a side project. The format was dead simple: /verify/?token=<base64 of "user:displayname">. Everything worked with test accounts like dave. Then a user signed up as María 你好, clicked the link, and got garbage back.
Three lines of debugging later I had re-learned a lesson that keeps biting people: Base64 encodes bytes, not characters. If you hand it a string, somebody first has to decide which bytes those characters become. Here is how I now handle Unicode Base64 in Python 3.11, Node 22, and when I just need a quick check, the browser.
The problem, stated precisely
The string héllo 你好 contains characters above the ASCII range. Base64 itself doesn't care — it only ever operates on bytes. The failure happens earlier, at the string-to-bytes step, and it fails differently in each language. In Python it refuses loudly. In Node it works. In the browser it throws. Same input, three outcomes, and each one teaches you something.
Method 1: Python 3.11
Python's base64 module (standard library, tested on Python 3.11.1) will not guess an encoding for you. Try to pass a str directly and it stops you:
import base64
base64.b64encode("héllo 你好")
# TypeError: a bytes-like object is required, not 'str'
That error message is annoying for about five seconds and then genuinely helpful. You are forced to name the encoding, which is exactly the decision that was going to bite you anyway:
import base64
s = "héllo 你好"
encoded = base64.b64encode(s.encode("utf-8")).decode("ascii")
print(encoded) # aMOpbGxvIOS9oOWlvQ==
decoded = base64.b64decode(encoded).decode("utf-8")
print(decoded) # héllo 你好
The .decode("ascii") at the end matters too, if you plan to put the result in a URL or a JSON payload. b64encode returns a bytes object, and concatenating bytes with a string is a TypeError waiting to happen. The full round trip here is 20 bytes: the input has 11 characters, but é costs 2 UTF-8 bytes and each Chinese character costs 3, and Base64 inflates that by roughly a third. For URL-safe output (filenames, path segments), swap in base64.urlsafe_b64encode, which uses - and _ instead of + and / per RFC 4648 section 5.
Method 2: Node 22
Node's Buffer makes the correct thing almost accidental, because Buffer always works in bytes and defaults to UTF-8:
// Node v22.13.0
const s = "héllo 你好";
const encoded = Buffer.from(s, "utf8").toString("base64");
console.log(encoded); // aMOpbGxvIOS9oOWlvQ==
const back = Buffer.from(encoded, "base64").toString("utf8");
console.log(back); // héllo 你好
Same output as Python, byte for byte. That consistency is worth verifying once and then trusting — a Base64 token generated in a Python job must decode correctly in a Node API, and with explicit UTF-8 on both ends it will.
The trap in Node is the browser-style global that also exists there. Node 22 still provides btoa() for web compatibility, and it carries the browser's limitations with it, which brings us to the third method and its failure.
Method 3: in the browser (or just paste it somewhere)
In a browser console, btoa("héllo 你好") does not quietly do the wrong thing — it throws:
Uncaught InvalidCharacterError: Failed to execute 'btoa' on 'Window':
The string to be encoded contains characters outside of the Latin1 range.
btoa() predates the modern web's Unicode habits. It only accepts characters up to code point U+00FF, one byte per character, legacy Latin-1 style. The correct modern fix is to encode to UTF-8 bytes first, then feed those bytes to btoa one byte at a time:
function utf8ToBase64(s) {
const bytes = new TextEncoder().encode(s);
return btoa(String.fromCharCode(...bytes));
}
// utf8ToBase64("héllo 你好") → "aMOpbGxvIOS9oOWlvQ=="
The same pattern is documented on the MDN btoa() page, along with the inverse using TextDecoder. I've used this trick enough times that now, when I'm debugging a token on someone else's machine and don't want to open an editor, I just paste the string into a free online Base64 encoder/decoder that is explicit about UTF-8, like Utilvy's Base64 tool. It runs entirely in the browser, so a token from a staging environment never leaves the machine. That's roughly the only reason I'd paste a credential-adjacent string into any web page at all.
Three pitfalls I've hit (with real output)
1. The mojibake round trip. Decode UTF-8 bytes but read them as Latin-1 and you get the classic ä½ å¥½ garbage. Real output from both Python and Node on the same input:
input: 你好
base64: 5L2g5aW9
decoded as latin-1: ä½ å¥½
decoded as utf-8: 你好
The bytes were fine all along. Only the read-back charset was wrong. Whenever decoded output "looks European in a bad way", it's almost always this.
2. The + that a URL turns into a space. I once put a standard Base64 token straight into a query string. Standard Base64 uses + and /, and a server-side query parser decoded that + as a space before my code ever saw it. Python 3.11, real output:
from urllib.parse import parse_qs
import base64
parse_qs("token=a+b/c==")
# {'token': ['a b/c==']}
base64.b64decode('a b/c==')
# b'i\xbf\xdc'
Note what did not happen: no exception. b64decode silently produced four wrong bytes. Corruption without an error is far worse than a crash. Either percent-encode the token (encodeURIComponent / quote), or generate it as base64url in the first place.
3. Double-encoding by accident. If you encode a string that is already Base64 text, you get valid Base64 of Base64. Nothing complains, and the string just gets 33% longer. If a decoded value still looks like YU1PcGx2..., decode it again before you panic about charset issues.
Quick reference
| Environment | Correct call | Fails on Unicode? |
|---|---|---|
| Python 3.11 | base64.b64encode(s.encode("utf-8")) |
Only if you pass str directly (TypeError) |
| Node 22 | Buffer.from(s, "utf8").toString("base64") |
No |
Browser btoa()
|
btoa(String.fromCharCode(...new TextEncoder().encode(s))) |
Yes, throws InvalidCharacterError raw |
The mental model that saves the most time: Base64 never sees characters, only bytes. Decide the byte encoding explicitly, prefer base64url anywhere near a URL, and keep a UTF-8-safe browser-based Base64 converter one tab away for sanity checks. More free browser-based utilities at utilvy.com.
Top comments (0)