JavaScript
Base64 Encode & Decode in JavaScript
Encode and decode Base64 in JavaScript using btoa(), atob(), and Buffer. Covers Unicode handling, files, and images.
Quick Reference
| Function | Direction | Environment |
|---|---|---|
| btoa(string) | String → Base64 | Browser + Node 16+ |
| atob(base64) | Base64 → String | Browser + Node 16+ |
| Buffer.from(str).toString('base64') | String → Base64 | Node.js |
| Buffer.from(b64,'base64').toString() | Base64 → String | Node.js |
Browser: btoa() and atob()
// Encode to Base64
const encoded = btoa('Hello, World!');
console.log(encoded); // "SGVsbG8sIFdvcmxkIQ=="
// Decode from Base64
const decoded = atob('SGVsbG8sIFdvcmxkIQ==');
console.log(decoded); // "Hello, World!"
Handling Unicode (UTF-8)
btoa() only works with Latin-1 characters. For Unicode strings (emojis, accented characters, CJK), encode to UTF-8 first:
// FAILS: btoa('Héllo 🌍') → error
// Solution: encode UTF-8 bytes first
function utf8ToBase64(str) {
return btoa(
new TextEncoder().encode(str)
.reduce((s, b) => s + String.fromCharCode(b), '')
);
}
function base64ToUtf8(b64) {
const binary = atob(b64);
const bytes = Uint8Array.from(binary, c => c.charCodeAt(0));
return new TextDecoder().decode(bytes);
}
const enc = utf8ToBase64('Héllo 🌍');
const dec = base64ToUtf8(enc);
console.log(dec); // "Héllo 🌍"
Node.js: Buffer
// Encode
const encoded = Buffer.from('Hello!').toString('base64');
// "SGVsbG8h"
// Decode
const decoded = Buffer.from('SGVsbG8h', 'base64').toString('utf-8');
// "Hello!"
// Works natively with Unicode
Buffer.from('Héllo 🌍').toString('base64');
// "SMOpbGxvIPCfjI0="
Encoding Files and Images
// Browser: File to Base64 via FileReader
function fileToBase64(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result.split(',')[1]);
reader.onerror = reject;
reader.readAsDataURL(file);
});
}
// Usage with <input type="file">
input.addEventListener('change', async (e) => {
const b64 = await fileToBase64(e.target.files[0]);
console.log(b64); // pure base64 string
});
// Create a data URL for inline images
const dataUrl = `data:image/png;base64,${b64}`;
img.src = dataUrl;
Base64 URL-Safe Variant
// Standard Base64 uses + / and = padding
// URL-safe variant uses - _ with no padding
function toBase64Url(str) {
return btoa(str)
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=+$/, '');
}
function fromBase64Url(b64url) {
let b64 = b64url.replace(/-/g, '+').replace(/_/g, '/');
while (b64.length % 4) b64 += '=';
return atob(b64);
}
// Used in: JWTs, URL parameters, filenames
What is Base64?
Base64 is a binary-to-text encoding that represents binary data using 64 ASCII characters (A-Z, a-z, 0-9, +, /). It increases data size by ~33% but ensures safe transport through text-only channels like JSON, HTML attributes, email (MIME), and URLs.
Last updated: 2026 • Browse all courses