Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference Β· Typed Arrays and Binary Data

btoa() and atob()

Reference for btoa() and atob(): encode binary strings as Base64 and decode them again, why Unicode text throws, and how to handle it with TextEncoder.

btoa() ("binary to ASCII") converts a string into Base64 text, and atob() ("ASCII to binary") converts Base64 text back. Base64 represents bytes using only letters, digits, +, / and = padding, so binary data can travel through text-only places such as JSON, URLs and data URLs.

Both functions work on binary strings: strings where each character stands for one byte (code units 0 to 255). They are not Unicode-aware, which is the source of most mistakes.

JavaScript
btoa("Hello");        // "SGVsbG8="
atob("SGVsbG8=");     // "Hello"

Try it

JS Encode and decode

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Unicode text and byte arrays

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
btoa(binaryString)
atob(base64String)
Name Description
binaryString A string whose characters are all in the range U+0000 to U+00FF.
base64String A Base64 string. ASCII whitespace is ignored; missing padding is tolerated when the length allows it.

Return value: btoa() returns the Base64 string; atob() returns a binary string with one character per decoded byte.

Exceptions: both throw a DOMException named InvalidCharacterError: btoa() for any character above U+00FF, atob() for characters outside the Base64 alphabet or an impossible length.

Usage notes

  • Unicode needs bytes first. Encode text to UTF-8 with TextEncoder, turn the bytes into a binary string, then call btoa(). Reverse the steps to decode. Skipping this gives errors or mangled text.
  • Base64 is not encryption. Anyone can decode it. It makes data about a third larger (4 output characters per 3 input bytes).
  • URL-safe Base64 uses - and _ instead of + and / and usually drops =. btoa() and atob() only know the standard alphabet; convert yourself as shown above. Newer engines add Uint8Array.prototype.toBase64() and Uint8Array.fromBase64() that handle both alphabets.
  • Large data. Building the binary string in a loop is fine for small inputs; for big files prefer FileReader.readAsDataURL() or the newer typed-array methods.
  • Data URLs. A Base64 payload goes after data:image/png;base64,.
  • Names. The legacy names come from Unix; read btoa as "binary to ASCII".

Browser support

btoa() and atob() work in all browsers, in Node.js and in other runtimes, and also in workers. The toBase64()/fromBase64() typed-array methods are new; check a compatibility table.