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
console.log(atob('Zm9vYmFy'));

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).


Hope you found this post useful. It was published . Please show your love and support by sharing this post.