W3docs

How to Encode and Decode Strings with Base64 in JavaScript

Read this tutorial and learn useful information about two JavaScript built-in functions which are used to convert a string to and from base64 encoding.

In this tutorial, you will learn how to encode a string to Base64 encoded format. JavaScript provides a built-in function named <kbd class="highlighted">btoa()</kbd> (binary-to-ASCII) to perform Base64 encoding.

Let's see how you can encode a string by using the <kbd class="highlighted">btoa()</kbd> function:

JavaScript btoa() to perform Base64 encoding

javascript— editable

Also, check our Base64 Encoder tool.

The default <kbd class="highlighted">btoa()</kbd> function expects a string where each character represents a single 8-bit byte (Latin-1 range 0–255). If the string contains characters outside this range (e.g., emojis or non-Latin scripts), it will throw an error.

To handle Unicode characters, you need to first convert the string to UTF-8 bytes, and then use the <kbd class="highlighted">btoa()</kbd> function to encode it to Base64:

JavaScript btoa() to perform Base64 encoding

javascript— editable

For modern environments, you can also use the TextEncoder and TextDecoder APIs for more robust Unicode handling.

There is a counterpart function, <kbd class="highlighted">atob()</kbd>, to convert from Base64 encoding back to a string. The <kbd class="highlighted">atob()</kbd> function returns a string where each character represents an 8-bit byte, meaning its value will be between 0 and 0xff.

JavaScript atob() to perform Base64 encoding

javascript— editable

Check out Base 64 Decoder tool.

Base64 encoding and decoding

Base64 is a binary-to-text encoding scheme that represents binary data in an ASCII string format by translating it into a radix-64 representation. It uses a character set consisting of Latin letters, digits, plus, and slash.