How to Base64-Encode a JavaScript String?

In JavaScript, you can use the btoa() method to encode a string into its Base64 equivalent.

For example:

// ES5+
const encodedStr = btoa('foobar');
console.log(encodedStr); // 'Zm9vYmFy'

Please note that the btoa() only supports single byte (8-bit) characters in the ASCII or Latin-1 character sets.

For example, if you pass a string to the btoa() method that is not in the ASCII or Latin-1 character sets, it will throw an error:

// ES5+
// Uncaught DOMException: Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.

You will need to convert the string to a binary string to make it compatible with the btoa() method for Base64 encoding.

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.