Tutorial

How to Encode and Decode Strings with Base64 in JavaScript

While this tutorial has content that we believe is of great benefit to our community, we have not yet tested or edited it to ensure you have an error-free learning experience. It's on our list, and we're working on it! You can help us out by using the "report an issue" button at the bottom of the tutorial.

Encoding and decoding a string in Base64 with JavaScript can be quite handy.

For that we have the btoa() and atob() functions. These two base64 helper functions are a core part of the HTML spec and available in all modern browsers.

  • btoa() encodes to Base64
  • atob() decodes from Base64
// 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!"

Copy and paste the examples above in your Chrome Console to see them working.

Common use cases for Base64

  • Packaging things like form input and JSON strings into a character set that’s safer to use in HTTP requests
  • Representing binary data in a way that’s compatible with HTML/JavaScript/CSS. - You can embed an image inline in a CSS or JavaScript file using Base64, for example.

What Base64 is not:

  • It’s in no way meant to be a secure encryption method,
  • It’s not a compression method, encoding a string to Base64 typically results in ~33% longer output.
Creative Commons License