Skip to main content

Base64 Encoding in JavaScript: btoa() and atob() Guide

Learn Base64 encoding in JavaScript using btoa(), atob(), and TextEncoder for Unicode. Free online encoder with ready-to-use JS code examples.

How to Base64 Encode in JavaScript

JavaScript provides two native functions for Base64 encoding: btoa() encodes a binary string to Base64, and atob() decodes it back. These functions are available in all modern browsers and have been part of the Web API since the earliest days of JavaScript in the browser.

Basic Usage: btoa() and atob()

// Encode a string to Base64
const encoded = btoa(\"Hello, World!\");
console.log(encoded); // \"SGVsbG8sIFdvcmxkIQ==\"

// Decode back from Base64
const decoded = atob(\"SGVsbG8sIFdvcmxkIQ==\");
console.log(decoded); // \"Hello, World!\"

Handling Unicode Characters

The btoa() function only works with Latin1 characters (code points 0-255). If your string contains Unicode characters like emojis or non-Latin scripts, you need to encode it first using TextEncoder:

// Unicode-safe Base64 encoding
function base64Encode(str) {
    const encoder = new TextEncoder();
    const bytes = encoder.encode(str);
    const binString = Array.from(bytes, (b) => String.fromCodePoint(b)).join(\"\");
    return btoa(binString);
}

// Unicode-safe Base64 decoding
function base64Decode(base64) {
    const binString = atob(base64);
    const bytes = Uint8Array.from(binString, (c) => c.codePointAt(0));
    return new TextDecoder().decode(bytes);
}

console.log(base64Encode(\"Hello 🌍\")); // Works with emojis!

Node.js Buffer Methods

In Node.js, the Buffer class provides Base64 encoding without the Latin1 limitation:

// Node.js Base64 encoding
const encoded = Buffer.from(\"Hello, World!\").toString(\"base64\");
const decoded = Buffer.from(encoded, \"base64\").toString(\"utf-8\");

// Encoding a file to Base64
const fs = require(\"fs\");
const fileBase64 = fs.readFileSync(\"image.png\").toString(\"base64\");

When to Use Base64 in JavaScript

  • Data URIs — embed images directly in HTML or CSS: data:image/png;base64,...
  • API payloads — send binary data through JSON APIs that only support text
  • LocalStorage — store binary data in browser storage which only accepts strings
  • Source maps — inline source maps in bundled JavaScript files

Browser Compatibility

btoa() and atob() are supported in all browsers including IE10+. The TextEncoder approach for Unicode is supported in Chrome 38+, Firefox 19+, Safari 10.1+, and Edge 79+. For older browsers, use a polyfill or the Buffer approach via a bundler.

Try Base64 Encoder/Decoder Free

Encode and decode Base64 strings.

Use Base64 Encoder/Decoder →