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, worldAny 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_X2QCommon mistake
Base64 is not encryption. Anyone can decode it, so do not hide passwords or secrets this way:
console.log(atob('cGFzc3dvcmQxMjM='));Output:
password123