How To Decode Base64 In Javascript

In this blog post, we will learn how to decode Base64 encoded strings in JavaScript. Base64 is a widely-used encoding scheme that allows you to convert binary data into a text format that can be easily transmitted over the internet. It is often used when transmitting images, files or other binary data in emails, web pages, and other text-based formats like JSON and XML.

Decoding Base64 Strings in JavaScript

Decoding a Base64 string in JavaScript is very simple, thanks to the built-in atob() function. The atob() function accepts a Base64 encoded string as an argument and returns the decoded text.

Here’s an example of how to use the atob() function:

        const base64String = 'SGVsbG8sIHdvcmxkIQ==';
        const decodedString = atob(base64String);
        console.log(decodedString); // Output: "Hello, world!"
        

If your Base64 string contains binary data, you may want to convert the decoded string into a Uint8Array to work with it more easily. Here’s how you can do that:

        const base64String = 'SGVsbG8sIHdvcmxkIQ==';
        const decodedString = atob(base64String);
        const byteArray = Uint8Array.from(decodedString, c => c.charCodeAt(0));
        console.log(byteArray); // Output: Uint8Array(13) [72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33]
        

Handling Errors

The atob() function will throw an error if the input string is not a valid Base64 encoded string. To handle this situation, you can use a try-catch block as shown in the following example:

        const base64String = 'SGVsbG8sIHdvcmxkIQ==='; // Invalid Base64 string

        try {
            const decodedString = atob(base64String);
            console.log(decodedString);
        } catch (error) {
            console.error('Error decoding Base64 string:', error.message);
        }
        

Conclusion

As we have seen, decoding Base64 strings in JavaScript is straightforward using the built-in atob() function. Additionally, you can convert the decoded string into a Uint8Array to work with binary data more easily. Remember to handle potential errors using a try-catch block when working with user-provided data or other uncertain sources.