Base64 is a widely used binary-to-text encoding scheme that transforms binary data into an equivalent ASCII character set by translating it into a radix-64 representation. It is commonly used for encoding and transporting data over media that are incompatible to transfer binary data. Base64 makes sure that the binary data doesn't change during transportation.
It is important to remember that Base64 is not an encryption or compression scheme. It only transforms the binary data into an ASCII character set that is extremely useful for transferring obfuscated strings over the network. For instance, a common example is sending an image or any other binary file to an email server that typically expects textual data. You have to first encode the binary file into a textual format, preferably ASCII.
btoa() — Base64 Encoding
btoa() function (stands for binary-to-ASCII) is used to create a Base64 encoded ASCII string from the binary data. It accepts the binary string as an argument and returns a Base64 encoded ASCII string.
The following example shows that how you can use
By default, the
btoa() method works fine for binary data consisting of 8-bit bytes. If your input data contains any character that has more than 8 bits, for instance, a Unicode character, the
btoa() function will throw an exception.
Here is an example:
If you execute the above code, you should see the following error output:
Uncaught DOMException: Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.
To encode Unicode characters, you first need to escape the input string to an array of 8-bit bytes (like UTF-8), and then use
btoa() to encode it to Base64 as shown in the following example:
atob() — Base64 Decoding
atob() to decode a Base64 encoding string:
atob() function works perfectly if the Base64 encoded input string only has 8-bit bytes. However, it fails to properly decode if the encoded input had 16-bit Unicode characters as shown in the following example:
As you can see above, the Unicode character is not properly decoded. To handle Unicode DOM strings, you have to convert the Base64 encoded bytes to percent-encoded strings, and then decode the percent-encoded string using
decodeURIComponent() like the following:
Of course, you can still choose to send binary data over the network. But it can be risky sometimes as not all applications and network communication devices can handle raw binary data. On the other hand, the ASCII character set is quite simple to handle for most applications.
Fore more information on Base64 encoding and decoding, take a look at this MDN guide.
👋 If you enjoy reading my articles and want to support me to continue creating free tutorials, ☕ Buy me a coffee (cost $5).