Yevhen Klymentiev
dark
light
console
darkness
y.klymentiev@gmail.com
Reusable Snippets|Practical utility code for everyday use — custom-built and ready to share

encodeBase64

Encodes a string to Base64 format.

TypeScript
Copied!
1/**
2 * Encodes a string to Base64 format.
3 *
4 * @param str - The input string to encode.
5 * @returns A Base64-encoded string.
6 */
7export function encodeBase64(str: string): string {
8  if (typeof window !== 'undefined' && typeof btoa === 'function') {
9    return btoa(unescape(encodeURIComponent(str)));
10  }
11
12  return Buffer.from(str, 'utf-8').toString('base64');
13}
  • Dual Environment Support

    Works seamlessly in both browser and Node.js environments by detecting btoa or falling back to Buffer.

  • Unicode-Safe Encoding

    Uses encodeURIComponent and unescape to properly handle multi-byte characters before Base64 encoding.

  • Minimal Dependencies

    Relies only on built-in APIs (btoa, Buffer) without introducing external libraries.

  • Consistent Output

    Guarantees a stable Base64 string regardless of environment differences in character encoding.

Tests | Examples

TypeScript
Copied!
1test('encodeBase64 - encodes plain ASCII text', () => {
2  expect(encodeBase64('Hello')).toBe('SGVsbG8=');
3});
4
5test('encodeBase64 - encodes empty string', () => {
6  expect(encodeBase64('')).toBe('');
7});
8
9test('encodeBase64 - encodes Unicode characters', () => {
10  expect(encodeBase64('Привет')).toBe('0J/RgNC40LLQtdGC');
11});
12
13test('encodeBase64 - encodes emojis', () => {
14  expect(encodeBase64('💡🔥')).toBe('8J+SqfCfkbE=');
15});

Common Use Cases

  • Data Serialization

    Encode text or binary data for safe transport in URLs, HTTP headers, or JSON payloads.

  • Authentication Tokens

    Prepare strings for use in Basic Auth headers or other token formats.

  • Embedding Binary in Text

    Encode images, fonts, or files as Base64 for inline use in HTML/CSS.

  • Secure Local Storage

    Store stringified and encoded sensitive information (e.g. settings) in localStorage or cookies.

Codebase: Utilities -> Encoding -> encodeBase64 | Yevhen Klymentiev