You can use btoa() and atob() to convert to and from base64 encoding.

There appears to be some confusion in the comments regarding what these functions accept/return, so…

  • btoa() accepts a “string” where each character represents an 8-bit byte – if you pass a string containing characters that can’t be represented in 8 bits, it will probably break. This isn’t a problem if you’re actually treating the string as a byte array, but if you’re trying to do something else then you’ll have to encode it first.

  • atob() returns a “string” where each character represents an 8-bit byte – that is, its value will be between 0 and 0xff. This does not mean it’s ASCII – presumably if you’re using this function at all, you expect to be working with binary data and not text.

See also:

  • How do I load binary image data using Javascript and XMLHttpRequest?

Most comments here are outdated. You can probably use both btoa() and atob(), unless you support really outdated browsers.

Check here:

  • https://caniuse.com/?search=atob
  • https://caniuse.com/?search=btoa

In 2025, all "evergreen" browsers offer toBase64 and fromBase64 to convert a Uint8Array to and from Base64 string. If your input is a Unicode string, not raw bytes, you can convert it to and from Uint8Array (of UTF-8 bytes) by TextEncoder and TextDecoder. See also another answer about this.

Answer from Shog9 on Stack Overflow
🌐
DigitalOcean
digitalocean.com › community › tutorials › how-to-encode-and-decode-strings-with-base64-in-javascript
How To Encode and Decode Strings with Base64 in JavaScript | DigitalOcean
October 1, 2025 - Learn how to encode and decode strings with Base64 in JavaScript. This guide covers btoa(), atob(), Buffer, modern APIs, and practical examples.
Discussions

Base64 encoding and decoding in client-side Javascript - Stack Overflow
Are there any methods in JavaScript that could be used to encode and decode a string using base64 encoding? More on stackoverflow.com
🌐 stackoverflow.com
Convert String to base64
Buffer.from creates a buffer (aka raw binary data), not an encoded string, the argument that you provide is the encoding the string is currently in. In order to change the encoding, you have to encode it again: Buffer.from("some string", "utf8").toString("base64") Similar to reverse the process: Buffer.from("c29tZSBzdHJpbmc=", "base64").toString("utf8") More on reddit.com
🌐 r/learnjavascript
5
5
March 6, 2023
Converting a base64 string to a blob in JavaScript | The Official Ionic Blog
This approach doesn't handle big files well. A while ago I implemented sequentially converting blob to base64 to be able to write big files to the filesystem. This allows for downloading big videos though the webview and prevents the app from crashing: https://github.com/digaus/CapacitorSaveBlob/blob/master/src/app/services/file.service.ts#L34 For reading big files however, using fetch is a great alternative. More on reddit.com
🌐 r/ionic
1
14
August 27, 2020
Send Blob or Base64 to Rails Controller

Are you familiar with using Pry for debugging?

More on reddit.com
🌐 r/rails
7
2
November 10, 2018
Top answer
1 of 16
1415

You can use btoa() and atob() to convert to and from base64 encoding.

There appears to be some confusion in the comments regarding what these functions accept/return, so…

  • btoa() accepts a “string” where each character represents an 8-bit byte – if you pass a string containing characters that can’t be represented in 8 bits, it will probably break. This isn’t a problem if you’re actually treating the string as a byte array, but if you’re trying to do something else then you’ll have to encode it first.

  • atob() returns a “string” where each character represents an 8-bit byte – that is, its value will be between 0 and 0xff. This does not mean it’s ASCII – presumably if you’re using this function at all, you expect to be working with binary data and not text.

See also:

  • How do I load binary image data using Javascript and XMLHttpRequest?

Most comments here are outdated. You can probably use both btoa() and atob(), unless you support really outdated browsers.

Check here:

  • https://caniuse.com/?search=atob
  • https://caniuse.com/?search=btoa

In 2025, all "evergreen" browsers offer toBase64 and fromBase64 to convert a Uint8Array to and from Base64 string. If your input is a Unicode string, not raw bytes, you can convert it to and from Uint8Array (of UTF-8 bytes) by TextEncoder and TextDecoder. See also another answer about this.

2 of 16
330

From here:

/**
*
*  Base64 encode / decode
*  http://www.webtoolkit.info/
*
**/
var Base64 = {

    // private property
    _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

    // public method for encoding
    encode : function (input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;

        input = Base64._utf8_encode(input);

        while (i < input.length) {

            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);

            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;

            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }

            output = output +
            this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
            this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
        }
        return output;
    },

    // public method for decoding
    decode : function (input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;

        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

        while (i < input.length) {

            enc1 = this._keyStr.indexOf(input.charAt(i++));
            enc2 = this._keyStr.indexOf(input.charAt(i++));
            enc3 = this._keyStr.indexOf(input.charAt(i++));
            enc4 = this._keyStr.indexOf(input.charAt(i++));

            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;

            output = output + String.fromCharCode(chr1);

            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }
        }

        output = Base64._utf8_decode(output);

        return output;
    },

    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }
        }
        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }
        }
        return string;
    }
}

Also, search for "JavaScript base64 encoding" turns up a lot of other options, and the above was the first one.

🌐
GeeksforGeeks
geeksforgeeks.org › javascript › javascript-encode-decode-a-string-to-base64
JavaScript | Encode/Decode a string to Base64 - GeeksforGeeks
May 28, 2024 - The Cross-Browser Method is used as a JavaScript library to encode/decode a string in any browser. Example 3: This examples encodes the string "This is GeeksForGeeks" by creating a Base64 object.
🌐
Vultr Docs
docs.vultr.com › javascript › examples › encode a string to base64
JavaScript Program to Encode a String to Base64
May 15, 2025 - This function converts an input ... Encoding strings into Base64 in JavaScript is straightforward with the built-in btoa() function....
🌐
Programiz
programiz.com › javascript › examples › encode-string-Base64
JavaScript Program to Encode a String to Base64
// program to encode a string to Base64 // defining the string const str = "Learning JavaScript"; // encoding the string const result = window.btoa(str); console.log(result); // decoding the string const result1 = window.atob(result); console.log(result1);
🌐
Squash
squash.io › how-to-encode-a-string-to-base64-in-javascript
How to Encode a String to Base64 in Javascript - Squash Labs
To encode a string to Base64 in JavaScript, you can use the built-in btoa() function.
Find elsewhere
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Glossary › Base64
Base64 - Glossary - MDN Web Docs - Mozilla
This has led to a common misconception that btoa can be used to encode arbitrary text data — for example, creating a Base64 data: URL of a text or HTML document. However, the byte-to-code-point correspondence only reliably holds true for code points up to 0x7f. Furthermore, code points over 0xff will cause btoa to throw an error due to exceeding the maximum value for 1 byte. The Window.btoa() "Unicode strings" section details how to work around this limitation when encoding arbitrary Unicode text.
🌐
W3docs
w3docs.com › home › code snippets › javascript › how to encode and decode strings with base64 in javascript
How to Encode and Decode Strings with Base64 in JavaScript | W3docs
In this tutorial, you will learn how to encode a string to Base64 encoded format. JavaScript provides a built-in function named <kbd class="highlighted">btoa()</kbd> (binary-to-ASCII) to perform Base64 encoding.
🌐
web.dev
web.dev › articles › the nuances of base64 encoding strings in javascript
The nuances of base64 encoding strings in JavaScript | Articles | web.dev
October 17, 2023 - This is stated explicitly on MDN: The btoa() method creates a Base64-encoded ASCII string from a binary string (i.e., a string in which each character in the string is treated as a byte of binary data).
🌐
Mastering JS
masteringjs.io › tutorials › fundamentals › encode-base64
Encode base64 in JavaScript - Mastering JS
The easiest way to convert a string to base64 is using the global btoa() function as follows.
🌐
freeCodeCamp
freecodecamp.org › news › encode-decode-html-base64-using-javascript
How to Encode and Decode HTML Base64 using JavaScript – JS Encoding Example
November 7, 2024 - These JavaScript helper functions are named after old Unix commands for converting binary to ASCII (btoa) and ASCII to binary (atob). You can encode a string to base64 in JavaScript using the btoa() function and decode a base64 string using ...
🌐
Stack Abuse
stackabuse.com › encoding-and-decoding-base64-strings-in-node-js
Encoding and Decoding Base64 Strings in Node.js
August 22, 2017 - These include to/from UTF-8, UCS2, Base64 or even Hex encodings. As you write code that deals with and manipulates data, you'll likely be using the Buffer object at some point. Take a look at the following example. Here we will encode a text string to Base64 using the Buffer object.
🌐
30 Seconds of Code
30secondsofcode.org › home › javascript › string › encode & decode strings with base64
How to encode and decode strings with Base64 in JavaScript - 30 seconds of code
December 25, 2023 - const stringToDecode = 'Zm9vYmFy'; const decodedString = atob(stringToDecode); // 'foobar' Luckily, both btoa() and atob() are supported in all modern browsers and Node.js since version 16.0.0. If, however, you need to support older Node.js versions, you will need to use the Buffer class to define your own btoa() and atob() functions. const btoa = str => Buffer.from(str, 'binary').toString('base64'); const atob = str => Buffer.from(str, 'base64').toString('binary'); const stringToEncode = 'foobar'; const encodedString = btoa(stringToEncode); // 'Zm9vYmFy' const stringToDecode = 'Zm9vYmFy'; const decodedString = atob(stringToDecode); // 'foobar'
🌐
Base64 Encode
base64encode.org
Base64 Encode and Decode - Online
Perform URL-safe encoding: Using ... the string unnecessarily longer. Enable this option to encode into an URL- and filename- friendly Base64 variant (RFC 4648 / Base64URL) where the "+" and "/" characters are respectively replaced by "-" and "_", as well as the padding "=" signs are omitted. Live mode: When you turn on this option the entered data is encoded immediately with your browser's built-in JavaScript functions, ...
🌐
DEV Community
dev.to › vvkkumar06 › converting-a-string-to-base64-manually-4ln2
Converting a string to Base64 manually - DEV Community
January 7, 2024 - If you notice the least significant number doesn't have 6 bits, then add 0 (zeroes) at the end to make it 6bits ... Just remember one thing here, if we add two zeroes then we will be using "=" at the end of base64 string if we will add 4 zeroes then we will be using "==" at the end of base64 string
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › API › Window › btoa
Window: btoa() method - Web APIs - MDN Web Docs - Mozilla
The btoa() method of the Window interface creates a Base64-encoded ASCII string from a binary string (i.e., a string in which each character in the string is treated as a byte of binary data). You can use this method to encode data which may otherwise cause communication problems, transmit ...
Top answer
1 of 16
291

Some browsers such as Firefox, Chrome, Safari, Opera and IE10+ can handle Base64 natively. Take a look at this Stackoverflow question. It's using btoa() and atob() functions.

For server-side JavaScript (Node), you can use Buffers to decode.

If you are going for a cross-browser solution, there are existing libraries like CryptoJS or code like:

http://ntt.cc/2008/01/19/base64-encoder-decoder-with-javascript.html (Archive)

With the latter, you need to thoroughly test the function for cross browser compatibility. And error has already been reported.

2 of 16
144

Internet Explorer 10+

// Define the string
var string = 'Hello World!';

// Encode the String
var encodedString = btoa(string);
console.log(encodedString); // Outputs: "SGVsbG8gV29ybGQh"

// Decode the String
var decodedString = atob(encodedString);
console.log(decodedString); // Outputs: "Hello World!"

Cross-Browser

Re-written and modularized UTF-8 and Base64 Javascript Encoding and Decoding Libraries / Modules for AMD, CommonJS, Nodejs and Browsers. Cross-browser compatible.


with Node.js

Here is how you encode normal text to base64 in Node.js:

//Buffer() requires a number, array or string as the first parameter, and an optional encoding type as the second parameter. 
// Default is utf8, possible encoding types are ascii, utf8, ucs2, base64, binary, and hex
var b = Buffer.from('JavaScript');
// If we don't use toString(), JavaScript assumes we want to convert the object to utf8.
// We can make it convert to other formats by passing the encoding type to toString().
var s = b.toString('base64');

And here is how you decode base64 encoded strings:

var b = Buffer.from('SmF2YVNjcmlwdA==', 'base64')
var s = b.toString();

with Dojo.js

To encode an array of bytes using dojox.encoding.base64:

var str = dojox.encoding.base64.encode(myByteArray);

To decode a base64-encoded string:

var bytes = dojox.encoding.base64.decode(str)

bower install angular-base64

<script src="bower_components/angular-base64/angular-base64.js"></script>

angular
    .module('myApp', ['base64'])
    .controller('myController', [

    '$base64', '$scope', 
    function($base64, $scope) {
    
        $scope.encoded = $base64.encode('a string');
        $scope.decoded = $base64.decode('YSBzdHJpbmc=');
}]);

But How?

If you would like to learn more about how base64 is encoded in general, and in JavaScript in-particular, I would recommend this article: Computer science in JavaScript: Base64 encoding

🌐
Medium
medium.com › @olenkadark › how-to-encode-and-decode-strings-with-base64-in-javascript-100ec741873d
How To Encode and Decode Strings with Base64 in JavaScript
May 31, 2024 - Let’s get to the exciting part: how do you encode strings to Base64 in JavaScript? The language provides a built-in function btoa() that you can use to encode data.