How to do Base64 Encoding in Javascript

Javascript contains two built-in functions named btoa() and atob() for encoding any binary data to the Base64 encoded (US-ASCII) format and decoding the encoded data back to binary data.

Base64 Encoding in Javascript (Works for UTF-8 strings: 8-bit bytes)

The default btoa() (binary-to-ascii) function works for binary data consisting of 8-bit bytes. However, if the input exceeds the 8-bit byte range, then it throws a Character Out Of Range exception.

Here is an example -

var str = "hello:world!?$*&()'-=@~";

// Encode the String
var encodedString = btoa(str);
console.log(encodedString); // aGVsbG86d29ybGQhPyQqJigpJy09QH4=

But, for input containing characters that exceed the 8-bit byte range (e.g. UTF-16), it throws an error -

var str = "Hello 😊";

// Encode the String
var encodedString = btoa(str);
# Output
Uncaught DOMException: Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range

Generic Base64 Encoding with support for 16-bit encoded strings

To handle Unicode characters, you need to first escape the string somehow to an array of 8-bit bytes and then use window.btoa() function to encode to Base64.

Here is one approach:

function base64EncodeUnicode(str) {
    // First we escape the string using encodeURIComponent to get the UTF-8 encoding of the characters, 
    // then we convert the percent encodings into raw bytes, and finally feed it to btoa() function.
    utf8Bytes = encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function(match, p1) {
            return String.fromCharCode('0x' + p1);
    });

    return btoa(utf8Bytes);
}

base64EncodeUnicode('Hello 😊')   // SGVsbG8g8J+Yig==

Other Approach: Convert UTF-16 to UTF-8 array of characters and then encode using btoa()

Also Read: Javascript Base64 Decode Example

Reference