Encode base64 in JavaScript
Aug 11, 2023
The easiest way to convert a string to base64 is using the global btoa()
function as follows.
btoa('hello'); // "aGVsbG8="
btoa()
is supported in all modern browsers and Node.js >= 16.0.0
.
Given that Node.js 14 was EOL in April 2023, you should use native btoa()
to convert strings to base64, unless you need to support older browsers or older Node.js versions.
Using Node.js Buffers
btoa()
is well supported in browsers, but is a relatively new addition to Node.js.
Thankfully, you can also use Node.js buffers to convert strings to base64 using buffers' toString()
method as follows.
const buf = Buffer.from('hello', 'utf8');
buf.toString('base64'); // "aGVsbG8="
Did you find this tutorial useful? Say thanks by starring our repo on GitHub!