Skip to content

toBase64

Encodes a string (as UTF-8) or raw bytes to Base64, without relying on btoa or Buffer, so it behaves the same in a browser, Node.js and GJS.

Available since v3.1.8

import { toBase64 } from '@helpers4/string';
// or, from the all-in-one package (same code, one install):
import { toBase64 } from 'helpers4/string';
toBase64(input: string | Uint8Array<ArrayBufferLike>, options: ToBase64Options): string
ParameterTypeDescription
inputstring | Uint8Array<ArrayBufferLike>The text to encode as UTF-8, or the bytes to encode as they are
optionsToBase64OptionsThe URL-safe alphabet and the padding — see ToBase64Options

string — The Base64 text

Non-ASCII text is encoded as UTF-8 first, so it round-trips with fromBase64.

toBase64('héllo')
// => 'aMOpbGxv'

Uses - and _ and drops the padding, ready for a query string or a JWT-like token.

toBase64(new Uint8Array([251, 255]), { urlSafe: true })
// => '-_8'

Options for toBase64.

interface ToBase64Options {
  padding?: boolean;
  urlSafe?: boolean;
}

View source on GitHub