Why Does This Happen?
Unlike in web browsers (where
btoa() is a global function), in Node.js versions below 16 the
btoa() 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: btoa is not defined console.log(btoa('foobar'));
How to Fix the Issue?
You can use the
Buffer.from() method instead to base64-encode a string, for example, like so:
const encodedStr = Buffer.from('foobar').toString('base64'); console.log(encodedStr); // 'Zm9vYmFy'
Please note that
btoa() 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 base64-encoding a 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.