Sylvaera/Blog/Privacy
Privacy

How to Encode Text and Strings to Base64 in JavaScript

July 14, 2026
4 min read
✍️ Sylvaera Team
HomeBlogHow to Encode Text and Strings to Base64 in JavaScript

Base64 encoding is an essential technique for transmitting binary data, API authentication keys, and sensitive tokens over text-based protocols like HTTP, JSON payloads, and email. In this tutorial, you will learn how Base64 encoding works, how to handle UTF-8 characters properly in JavaScript, and how to create URL-safe Base64 strings.

What is Base64 Encoding?

Base64 is a binary-to-text encoding scheme that represents binary data using a set of 64 ASCII characters: uppercase letters (A–Z), lowercase letters (a–z), digits (0–9), and two symbols (+ and /). Because text-based communication protocols are designed to process human-readable characters, raw binary data can be corrupted during transmission. Base64 ensures that arbitrary bytes are safely transported without modification.

How the Base64 Algorithm Works

The encoding process divides input data into 24-bit chunks (three 8-bit bytes). Each 24-bit chunk is then split into four 6-bit units. Since 6 bits represent values from 0 to 63, each 6-bit unit maps directly to one of the 64 characters in the Base64 index table:

  • 3 Bytes of Input: Yields exactly 4 Base64 characters (a 33% size increase).
  • Padding (=): If the input byte length is not divisible by 3, one or two padding characters (=) are appended at the end to complete the 4-character group.

Encoding Strings in JavaScript: Standard vs. UTF-8

The standard browser function btoa() (binary to ASCII) handles Latin1 characters. However, if your string contains UTF-8 characters such as emojis, non-Latin alphabets, or special symbols, btoa() throws an invalid character error. Here is the modern approach using the browser's native TextEncoder API:

Standard JavaScript Base64 Encoding

// Modern UTF-8 safe Base64 encoding function
function encodeBase64(text) {
  const bytes = new TextEncoder().encode(text);
  let binaryString = '';
  bytes.forEach((byte) => {
    binaryString += String.fromCharCode(byte);
  });
  return window.btoa(binaryString);
}

// Example usage:
const payload = "Hello, Sylvaera! 🌿 User: Admin";
const encoded = encodeBase64(payload);
console.log(encoded); // SGVsbG8sIFN5bHZhZXJhISDwn44oIFVzZXI6IEFkbWlu

What is URL-Safe Base64?

In standard Base64, the characters + and / have reserved meanings in URL paths and query parameters. When transmitting Base64 payloads inside URLs (such as OAuth tokens, JWT claims, or verification links), URL-safe Base64 replaces these characters:

  • + is replaced with - (hyphen)
  • / is replaced with _ (underscore)
  • Optional: Trailing padding characters (=) can be omitted because padding length can be calculated from string length.

URL-Safe Encoding Implementation

function encodeUrlSafeBase64(text, removePadding = true) {
  let b64 = encodeBase64(text);
  b64 = b64.replace(/\+/g, '-').replace(/\//g, '_');
  if (removePadding) {
    b64 = b64.replace(/=+$/, '');
  }
  return b64;
}

const safeToken = encodeUrlSafeBase64("auth_token_secret_12345");
console.log(safeToken);

Privacy and Security Best Practices

It is important to remember that Base64 is an encoding format, not encryption. Anyone can decode a Base64 string back to its original bytes. Never use Base64 alone to protect sensitive passwords or customer PII. When privacy is required, combine Base64 with data masking or strong encryption algorithms.

Encode Text Online with Sylvaera

Need to encode strings, API tokens, or webhook secrets instantly without installing packages? Use Sylvaera's Base64 Encoder. It runs 100% client-side in your browser, guaranteeing that your sensitive credentials never touch an external server.

Need realistic synthetic test data?

Try Sylvaera's premium platform capabilities. Generate datasets, format JSON, mock API responses, anonymize PII and convert formats instantly.

Get Started Free →