How Do You Encode a String to Base64 in JavaScript?
Use btoa() in browsers and Node.js 16+. The btoa() function accepts a binary string (each character representing a single byte with code point U+0000 through U+00FF) and returns a Base64-encoded ASCII string. It is available in all modern browsers and runs synchronously.
// Encode a string to Base64
const encoded = btoa('Hello, World!');
console.log(encoded); // "SGVsbG8sIFdvcmxkIQ=="
The btoa() function name stands for "binary to ASCII." It processes the input string one character at a time, reading the low byte of each character's code point. The output follows the standard Base64 alphabet (A-Z, a-z, 0-9, +, /) with = padding. For background on the encoding format, see What is Base64 Encoding?. To encode text without writing code, use the Base64 text encoder.
How Do You Decode Base64 to a String in JavaScript?
Use atob() to decode. The atob() function takes a Base64-encoded string and returns the decoded binary string. It accepts standard Base64 characters (A-Z, a-z, 0-9, +, /, =) and ignores whitespace in the input.
// Decode Base64 to a string
const decoded = atob('SGVsbG8sIFdvcmxkIQ==');
console.log(decoded); // "Hello, World!"
The atob() function name stands for "ASCII to binary." Each group of 4 Base64 characters decodes to 3 bytes. If the input contains characters outside the Base64 alphabet or has incorrect padding, atob() throws a DOMException. To decode Base64 strings interactively, use the Base64 text decoder.
How Do You Handle Unicode Text with Base64 in JavaScript?
The btoa() function only handles Latin-1 characters (code points U+0000 to U+00FF). Passing Unicode characters such as emoji, Chinese, Arabic, or accented characters above U+00FF causes an InvalidCharacterError. Use TextEncoder and TextDecoder with Uint8Array conversion to handle full UTF-8 text.
// Encode UTF-8 string to Base64
function utf8ToBase64(str) {
const bytes = new TextEncoder().encode(str);
const binary = Array.from(bytes, b => String.fromCharCode(b)).join('');
return btoa(binary);
}
// Decode Base64 to UTF-8 string
function base64ToUtf8(base64) {
const binary = atob(base64);
const bytes = Uint8Array.from(binary, c => c.charCodeAt(0));
return new TextDecoder().decode(bytes);
}
// Usage
const encoded = utf8ToBase64('Hello 🌍');
console.log(encoded); // "SGVsbG8g8J+MjQ=="
console.log(base64ToUtf8(encoded)); // "Hello 🌍"
TextEncoder.encode() converts a JavaScript string to a Uint8Array of UTF-8 bytes. The Array.from() call maps each byte to a Latin-1 character that btoa() can process. The decoding path reverses this: atob() produces a binary string, Uint8Array.from() extracts the byte values, and TextDecoder.decode() interprets them as UTF-8. For details on how Base64 handles different character sets, see the Base64 character table.
How Do You Convert an Image to Base64 in JavaScript?
Use FileReader.readAsDataURL() to convert an image file to a Base64 data URI in the browser. The readAsDataURL() method reads a File or Blob object and produces a string in the format data:[mimetype];base64,[encoded data]. This operation is asynchronous and fires the onload event when complete.
// Convert an image file to Base64 data URI
const input = document.querySelector('input[type="file"]');
input.addEventListener('change', (e) => {
const file = e.target.files[0];
const reader = new FileReader();
reader.onload = () => {
const dataUri = reader.result;
console.log(dataUri);
// "data:image/png;base64,iVBORw0KGgo..."
};
reader.readAsDataURL(file);
});
The resulting data URI can be assigned directly to an <img> element's src attribute or used in CSS background-image properties. For a ready-to-use tool that handles image encoding with preview, drag-and-drop, and copy-to-clipboard, use the Base64 image encoder. For information about embedding Base64 images in HTML and CSS, see the data URI guide.
How Do You Use Base64 in Node.js?
Use the Buffer class in Node.js. Buffer.from(string).toString('base64') encodes a string to Base64. Buffer.from(base64String, 'base64').toString() decodes Base64 back to a string. The Buffer class handles UTF-8 by default, so no additional conversion is needed for Unicode characters.
// Node.js: Encode string to Base64
const encoded = Buffer.from('Hello, World!').toString('base64');
console.log(encoded); // "SGVsbG8sIFdvcmxkIQ=="
// Node.js: Decode Base64 to string
const decoded = Buffer.from('SGVsbG8sIFdvcmxkIQ==', 'base64').toString();
console.log(decoded); // "Hello, World!"
// Node.js: Encode UTF-8 (Unicode works directly)
const emoji = Buffer.from('Hello 🌍').toString('base64');
console.log(emoji); // "SGVsbG8g8J+MjQ=="
// Node.js: Encode a file to Base64
const fs = require('fs');
const fileBase64 = fs.readFileSync('image.png').toString('base64');
const dataUri = `data:image/png;base64,${fileBase64}`;
Buffer.from() accepts an encoding parameter. When encoding to Base64, pass the source string with the default UTF-8 encoding, then call .toString('base64'). When decoding, specify 'base64' as the second argument to Buffer.from() and call .toString('utf-8') for the output. Node.js also supports btoa() and atob() starting from Node.js 16.0.0.
What Are the JavaScript Base64 Functions?
JavaScript provides 6 built-in APIs for Base64 operations across browser and Node.js environments. The table below lists each function, its runtime environment, primary purpose, and Unicode support level.
| Function / API | Environment | Purpose | Unicode Support |
|---|---|---|---|
btoa() | Browser, Node 16+ | Encode binary string to Base64 | Latin-1 only |
atob() | Browser, Node 16+ | Decode Base64 to binary string | Latin-1 only |
Buffer.from().toString('base64') | Node.js | Encode string or bytes to Base64 | Full UTF-8 |
Buffer.from(str, 'base64') | Node.js | Decode Base64 to Buffer | Full UTF-8 |
TextEncoder + btoa | Browser | Encode UTF-8 string to Base64 | Full UTF-8 |
FileReader.readAsDataURL | Browser | Convert File/Blob to data URI | N/A (binary) |
For URL-safe Base64 output (replacing + with - and / with _), apply a string replacement after encoding or use the URL-safe Base64 encoder. In Node.js, use Buffer.from(str).toString('base64url') (available since Node.js 15.7.0) for direct URL-safe output.
What Are Common JavaScript Base64 Errors?
Two errors occur frequently when using Base64 in JavaScript: InvalidCharacterError from btoa() when encoding non-Latin-1 characters, and DOMException from atob() when decoding invalid Base64 strings. Both are catchable with try/catch.
InvalidCharacterError from btoa()
Calling btoa() with a string containing characters above code point U+00FF throws InvalidCharacterError. This includes emoji, CJK characters, Cyrillic, and many accented characters.
// This throws InvalidCharacterError
try {
btoa('Hello 🌍');
} catch (e) {
console.error(e.name); // "InvalidCharacterError"
console.error(e.message); // "The string to be encoded contains characters outside of the Latin1 range."
}
// Fix: use TextEncoder
const bytes = new TextEncoder().encode('Hello 🌍');
const binary = Array.from(bytes, b => String.fromCharCode(b)).join('');
const encoded = btoa(binary); // Works correctly
DOMException from atob()
Calling atob() with a string that contains characters outside the Base64 alphabet or has incorrect length/padding throws a DOMException.
// This throws DOMException
try {
atob('not-valid-base64!!!');
} catch (e) {
console.error(e.name); // "InvalidCharacterError"
console.error(e.message); // "The string to be decoded is not correctly encoded."
}
// Fix: validate before decoding
function isValidBase64(str) {
try {
atob(str);
return true;
} catch {
return false;
}
}
Use the Base64 validator to check whether a string is valid Base64 before processing it in your code.
Frequently Asked Questions
Does JavaScript have built-in Base64 support?
Yes. JavaScript provides btoa() and atob() as built-in browser APIs for Base64 encoding and decoding. These functions are available in all modern browsers and in Node.js 16+. No external library or npm package is required for standard Base64 operations.
Why does btoa() fail with emoji or Unicode characters?
btoa() only accepts Latin-1 (ISO 8859-1) characters, which are code points U+0000 through U+00FF. Emoji and most Unicode characters have code points above U+00FF, causing btoa() to throw an InvalidCharacterError. Use TextEncoder to convert the string to UTF-8 bytes first, then encode those bytes with btoa().
Is Base64 encoding in JavaScript synchronous?
btoa() and atob() are synchronous functions that return results immediately. FileReader.readAsDataURL() is asynchronous and requires an onload callback or event listener to access the Base64 result. Buffer.from().toString('base64') in Node.js is synchronous.
Can I use Base64 in JavaScript without any library?
Yes. Native browser APIs (btoa, atob, FileReader, TextEncoder, TextDecoder) and Node.js Buffer handle all Base64 encoding and decoding operations without any external library. These built-in functions cover standard Base64, UTF-8 handling, and file-to-Base64 conversion.
How do I Base64 encode a file in the browser?
Use FileReader.readAsDataURL() to convert a file to a Base64 data URI. Call readAsDataURL() on a File object from an <input type="file"> element, then access the result in the onload callback via reader.result. The result contains the full data URI including the MIME type prefix. For a drag-and-drop interface, use the Base64 image encoder.