What to Look Out For When Encoding to Base64 in JavaScript
Encoding to base64 and decoding in JavaScript can be done by using the built-in btoa
and atob
functions respectively.
Did you know that the function names come from Unix commands? btoa
stands for binary to ASCII while atob
stands for ASCII to binary.
Both of these functions take in a string as a parameter that can be encoded and then decoded later as well, and both of them returned a string as well. For example:
const encodedString = btoa('Encode me!')
// This will produce:
'RW5jb2RlIG1lIQ=='
const decodedString = atob('RW5jb2RlIG1lIQ==')
// This will produce the original string:
'Encode me!'
Keep in mind that when using characters other than Latin, for example, Cyrillic or an emoji, you will run into the following error:
Uncaught DOMException: Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.
To resolve btoa
character range errors, you need to first escape the string with encodeURIComponent
before encoding it to base64. You can fix the above error in the following way:
// This will throw "Failed to execute 'btoa' on 'Window'"
btoa('π₯')
// This will result in 'JUYwJTlGJUE1JTkx'
btoa(encodeURIComponent('π₯'))
// You can decode it in the following way:
decodeURIComponent(atob('JUYwJTlGJUE1JTkx'))
When would you want to use base64 encoding?
A common use case for base64 encoding is when you want to store data in your HTML or CSS files in a compatible way. For example, you might be already familiar with inlining images using a base64 string as an attribute.
<img src="data:image/png;base64,..." />
background: url(data:image/png;base64,...);
When should you not use base64 encoding?
If you are looking to compress your data, you should not use base64 encoding, as it is not meant for compression. In fact, when converting strings to base64, your output will be at least 33% larger. The fewer characters you are going to encode, the larger the end result will be. For example, if you try to encode β1β, you will get the following:
btoa('1') -> 'MQ=='
If you are looking to encrypt your data, you also donβt want to use base64 encoding. Although at first sight, it may look like an unintelligible string, it can be easily recognized as a base64 string and can easily be decoded as well using atob
.
Rocket Launch Your Career
Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies: