JavaScript atob() and btoa() Functions
Quick reference for JavaScript's built-in Base64 encoding and decoding functions.
|
btoa() - Encode to Base64
The `btoa()` function creates a Base64-encoded ASCII string from binary data.
// Basic usage
const encoded = btoa('Hello World');
console.log(encoded); // "SGVsbG8gV29ybGQ="
// Encoding JSON
const json = JSON.stringify({ name: 'John', age: 30 });
const encodedJson = btoa(json);
console.log(encodedJson); // "eyJuYW1lIjoiSm9obiIsImFnZSI6MzB9"
- > Only accepts ASCII characters (0-255)
- > Throws error for Unicode characters
- > Available in all modern browsers and Node.js 16+
atob() - Decode from Base64
The `atob()` function decodes a Base64-encoded string.
// Basic usage
const decoded = atob('SGVsbG8gV29ybGQ=');
console.log(decoded); // "Hello World"
// Decoding JSON
const decodedJson = atob('eyJuYW1lIjoiSm9obiIsImFnZSI6MzB9');
const data = JSON.parse(decodedJson);
console.log(data); // { name: 'John', age: 30 }
- > Returns binary string
- > Throws error for invalid Base64
- > Case-sensitive input
Handling Unicode
For Unicode strings, combine with TextEncoder/TextDecoder.
// Encode Unicode
function encodeUnicode(str) {
const bytes = new TextEncoder().encode(str);
const binString = String.fromCharCode(...bytes);
return btoa(binString);
}
// Decode Unicode
function decodeUnicode(base64) {
const binString = atob(base64);
const bytes = Uint8Array.from(binString, c => c.charCodeAt(0));
return new TextDecoder().decode(bytes);
}
// Example
const encoded = encodeUnicode('你好世界 🌍');
const decoded = decodeUnicode(encoded);
console.log(decoded); // "你好世界 🌍"
Common Use Cases
Practical applications in web development.
Error Handling
Best practices for robust code.
function safeBase64Decode(str) {
try {
return atob(str);
} catch (e) {
console.error('Invalid Base64:', e);
return null;
}
}
function safeBase64Encode(str) {
try {
return btoa(str);
} catch (e) {
// Likely Unicode issue
return btoa(unescape(encodeURIComponent(str)));
}
}
Browser & Node.js Support
Availability across environments.
// Node.js fallback for older versions
if (typeof btoa === 'undefined') {
global.btoa = (str) => Buffer.from(str, 'binary').toString('base64');
global.atob = (b64) => Buffer.from(b64, 'base64').toString('binary');
}
Performance Tips
Optimize Base64 operations.
// Performance comparison
const cache = new Map();
function cachedBtoa(str) {
if (!cache.has(str)) {
cache.set(str, btoa(str));
}
return cache.get(str);
}
- > Cache encoded values for repeated use
- > Use streaming for large files
- > Consider alternatives for binary data (ArrayBuffer, Blob)
- > Batch operations when possible