How to encode a string in base64 in JavaScript

Encoding strings to base64 is essential for data transmission, API authentication, image data handling, and implementing features like email attachments or secure data storage in JavaScript applications. With over 25 years of experience in software development and as the creator of CoreUI, I’ve implemented base64 encoding extensively in components like file upload systems, API integrations, and data export features where converting text to a safe, transmittable format is crucial for reliable data handling. From my extensive expertise, the most direct and browser-native solution is using the built-in btoa() function, which provides standard base64 encoding. This approach is efficient, widely supported, and specifically designed for binary-to-ASCII conversion in web environments.

Use the btoa() function to encode a string into base64 format.

const text = 'Hello World'
const encoded = btoa(text)
// Result: 'SGVsbG8gV29ybGQ='

The btoa() function (binary-to-ASCII) converts a string into its base64 representation, creating a safe ASCII string that can be transmitted over text-based protocols. In this example, btoa('Hello World') produces ‘SGVsbG8gV29ybGQ=’, which is the base64-encoded version. The function only works with strings containing characters in the 0-255 range (Latin-1). For Unicode strings, you need to first encode them using encodeURIComponent() and then btoa(), or use the more modern TextEncoder approach.

Best Practice Note:

This is the same approach we use in CoreUI components for encoding data in API requests, handling file uploads, and creating data URIs across our component ecosystem. For Unicode strings, use: btoa(encodeURIComponent(text).replace(/%([0-9A-F]{2})/g, (match, p1) => String.fromCharCode('0x' + p1))). In Node.js, use Buffer.from(text).toString('base64'). The btoa() function is supported in all modern browsers but throws errors on invalid characters.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author