How to Decode a Base64-Encoded JavaScript String?

In JavaScript, you can use the atob() method to decode a Base64-encoded string back to its original form.

For example:

// ES5+
const decodedStr = atob('Zm9vYmFy');
console.log(decodedStr); // 'foobar'

Please note that you may have to do some additional work to decode a multibyte encoded string.

Passing invalid base64 strings to atob() will throw an error. For example, the following string contains an invalid character (_) and would throw an error:

// ES5+
// Uncaught DOMException: Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded.
atob('8J+mig__');

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.