Base64 Explained: Encoding, UTF-8, Base64URL and btoa Errors
Base64 turns any bytes – an image, a file, binary data – into plain text made of 64 safe characters. You meet it in data URLs, email attachments, JWTs, API keys and HTTP Basic auth. This guide explains how it works, when to use it, and the bugs that come with it: the btoa Unicode error, padding and Base64URL. Outputs were produced in Chrome, Node.js 24 and Python.
How it works in one minute
Base64 takes 3 bytes (24 bits) at a time and writes them as 4 characters of 6 bits each, using A–Z, a–z, 0–9, + and /. When the input isn’t a multiple of 3 bytes, = pads the end:
"a" → YQ==
"ab" → YWI=
"abc" → YWJjBecause 3 bytes become 4 characters, Base64 output is about 33% bigger than the input: 3,000 bytes become 4,000 characters.
When to use it (and when not)
- Yes: putting binary data where only text is allowed – a small image in JSON or a data URL, an attachment in email, bytes in an environment variable.
- No: uploading big files through a JSON API. Send the file as
multipart/form-dataor upload it directly instead – you avoid the 33% overhead and the memory cost of huge strings.
JavaScript: btoa and atob
btoa('hello') // 'aGVsbG8=' encode
atob('aGVsbG8=') // 'hello' decodeThen you try it on real text:
btoa('café ✓')
// InvalidCharacterError: Failed to execute 'btoa' on 'Window':
// The string to be encoded contains characters outside of the Latin1 range.btoa only accepts characters with codes 0–255 (Latin-1). Worse, btoa('café') does not fail: it returns Y2Fm6Q==, the Latin-1 bytes. Decode that as UTF-8 in Python or on a server, and you get caf�. The fix is to encode the text to UTF-8 bytes first:
// text → Base64 (UTF-8)
function encodeBase64(text) {
const bytes = new TextEncoder().encode(text)
let binary = ''
for (const b of bytes) binary += String.fromCharCode(b)
return btoa(binary)
}
// Base64 → text (UTF-8)
function decodeBase64(b64) {
const binary = atob(b64)
return new TextDecoder().decode(Uint8Array.from(binary, (c) => c.charCodeAt(0)))
}
encodeBase64('café ✓') // 'Y2Fmw6kg4pyT'
decodeBase64('Y2Fmw6kg4pyT') // 'café ✓'Uint8Array.prototype.toBase64() and Uint8Array.fromBase64(), which do this without tricks. They’re not available everywhere yet (Node.js 24 doesn’t have them), so keep a fallback.In Node.js, use Buffer, which handles UTF-8 for you:
Buffer.from('café ✓').toString('base64') // 'Y2Fmw6kg4pyT'
Buffer.from('Y2Fmw6kg4pyT', 'base64').toString() // 'café ✓'Base64URL
+, / and = have special meanings in URLs and file names. Base64URL replaces them: + → -, / → _, and usually drops the = padding. JWTs use Base64URL, which is why a JWT never contains + or /.
const standard = '+/+/'
const urlSafe = standard.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '') // '-_-_'
Buffer.from([251, 255, 191]).toString('base64url') // '-_-_' (Node.js)Mixing the two variants is a common bug: atob('a-_b') throws “The string to be decoded is not correctly encoded”. Convert - and _ back to + and / before calling atob. Missing padding is fine for atob (atob('aGVsbG8') returns hello), but not for Python.
Python
import base64
base64.b64encode("café ✓".encode("utf-8")) # b'Y2Fmw6kg4pyT'
base64.b64decode("Y2Fmw6kg4pyT").decode("utf-8") # 'café ✓'
base64.urlsafe_b64encode(bytes([251, 255, 191])) # b'-_-_'
base64.b64decode("aGVsbG8")
# binascii.Error: Incorrect padding
s = "aGVsbG8"
base64.b64decode(s + "=" * (-len(s) % 4)) # b'hello' – add the missing paddingPython works with bytes: encode your text with .encode("utf-8") before Base64, and .decode("utf-8") after.
Command line
$ printf 'hello' | base64
aGVsbG8=
$ echo 'aGVsbG8=' | base64 -d
helloUse printf (or echo -n) when encoding: plain echo adds a newline, so echo hello | base64 encodes hello\n and gives a different result.
Where you’ll see Base64
- JWTs – the header and payload are Base64URL-encoded JSON. Read them with the JWT Decoder, or see how to decode a JWT.
- HTTP Basic auth –
Authorization: Basic dXNlcjpwYXNzis justuser:pass. - Data URLs –
data:image/png;base64,iVBORw0… - Kubernetes secrets – values are Base64, not encrypted.
Need code for a specific language? See Base64 encode and decode examples for the shell, JavaScript, Python, Java, C#, PHP and Go.