How to Encode and Decode Base64 (With Examples)
Base64 encodes binary data as ASCII text, making it safe to transmit through systems that only handle text โ email, JSON, URLs, and HTML. It's not encryption (anyone can decode it) and it increases size by 33%, but it's essential for embedding images in CSS, sending file attachments, and working with APIs.
- Encode and decode Base64 strings in JavaScript, Python, and the command line.
- What Is Base64?.
- Covers base64 in javascript.
- Covers common use cases.
- When Not to Use Base64.
What Is Base64?
Base64 converts binary data into a string using 64 characters: A-Z, a-z, 0-9, +, and /. Every 3 bytes of input become 4 characters of output, with = padding at the end if needed. The name comes from the 64-character alphabet. Base64 is used because many protocols and formats (email, JSON, XML, CSS) can only transport text characters safely. Binary data like images, fonts, or encrypted payloads would be corrupted without encoding.
Base64 in JavaScript
Browser JavaScript uses btoa() and atob():
// Encode
const encoded = btoa('Hello World'); // 'SGVsbG8gV29ybGQ='
// Decode
const decoded = atob('SGVsbG8gV29ybGQ='); // 'Hello World'
For Unicode strings, encode to UTF-8 first:
const encoded = btoa(unescape(encodeURIComponent('Hรฉllo')));
Node.js uses Buffer:
Buffer.from('Hello').toString('base64');
Buffer.from('SGVsbG8=', 'base64').toString();
Common Use Cases
Data URIs in CSS: embedding small images directly in stylesheets avoids an HTTP request. Format: url(data:image/png;base64,iVBOR...). JWT tokens: the header and payload of a JWT are Base64URL-encoded (a URL-safe variant using - and _ instead of + and /). Email attachments: MIME encoding uses Base64 to embed binary files in text-only email. API payloads: sending binary data (files, images) in JSON request bodies.
background-size animation or @property registered custom properties instead.When Not to Use Base64
Base64 increases data size by 33%. Don't use it for large files โ serve them as binary with proper Content-Type headers instead. Don't use it for encryption or security โ Base64 is encoding, not encryption. Anyone can decode it. Don't embed large images as data URIs โ the Base64 string can't be cached independently and bloats your CSS. For quick encoding/decoding, use the Base64 Encoder tool โ paste any text or file and get instant results.