Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to encode and decode Base64

Short answer

btoa() encodes a string to Base64, atob() decodes it back:

const encoded = btoa('Hello, world');
 
console.log(encoded);
console.log(atob(encoded));

Output:

SGVsbG8sIHdvcmxk
Hello, world

Any letters

btoa() works only with Latin-1 characters. For other text, turn the string into bytes with TextEncoder first:

const toBase64 = (text) => btoa(String.fromCharCode(...new TextEncoder().encode(text)));
const fromBase64 = (base64) => new TextDecoder().decode(Uint8Array.from(atob(base64), (char) => char.charCodeAt(0)));
 
const encoded = toBase64('Привет 👋');
 
console.log(encoded);
console.log(fromBase64(encoded));

Output:

0J/RgNC40LLQtdGCIPCfkYs=
Привет 👋

Base64 for URLs

The characters +, / and = have a meaning in addresses. The URL-safe variant replaces them:

const base64url = btoa('subjects?_d').replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, '');
 
console.log(btoa('subjects?_d'));
console.log(base64url);

Output:

c3ViamVjdHM/X2Q=
c3ViamVjdHM_X2Q

Common mistake

Base64 is not encryption. Anyone can decode it, so do not hide passwords or secrets this way:

console.log(atob('cGFzc3dvcmQxMjM='));

Output:

password123

Functions used in this recipe

  • btoa — Encodes a string to Base64.
  • atob — Decodes a Base64 string.

Thanks for reading!

Donate to the site — we work hard for you.