How to Fix "atob is not defined" Error in Node.js?

Why Does This Happen?

Unlike in web browsers (where atob() is a global function), in Node.js versions below 16 the atob() function is not available in the global namespace. For this reason, when you try to access it directly, it throws a ReferenceError, for example, like in the following case:

// ReferenceError: atob is not defined

How to Fix the Issue?

You can use the Buffer.from() method instead to decode a base64-encoded string, for example, like so:

const decodedStr = Buffer.from('Zm9vYmFy', 'base64').toString('utf8');

console.log(decodedStr); // 'foobar'

Please note that atob() was added to the global namespace in Node.js v16 (as legacy support). Therefore, you can also upgrade Node.js to v16+. However, it is recommended to use the Buffer.from() method for decoding a base64-encoded string (as it can handle characters beyond the ASCII range).

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.