Base64 URL Encoder and Decoder with UTF-8 support – base64url

Category: Javascript | September 17, 2024
Authorsupabase-community
Last UpdateSeptember 17, 2024
LicenseMIT
Tags
Views83 views
Base64 URL Encoder and Decoder with UTF-8 support – base64url

Base64url is a lightweight, straightforward TypeScript library that encodes and decodes Base64 URLs for JavaScript strings with comprehensive UTF-8 support.

It can be useful for developers working with JSON Web Tokens (JWTs) or those involved in encoding JavaScript strings to UTF-8 for binary formats.

How to use it:

1. Download the package and import the following modules into your project.

import {
  stringToBase64URL,
  stringFromBase64URL,
  stringToUTF8,
  stringFromUTF8,
  byteToBase64URL,
  byteFromBase64URL
} from './src/base64url.ts';

2. To encode a string to Base64 URL, you can use the stringToBase64URL function. And to decode a Base64 URL string back to its original form, you simply call stringFromBase64URL.

stringToBase64URL('CSSScript');
// => Q1NTU2NyaXB0
stringFromBase64URL('Q1NTU2NyaXB0')
// => CSSScript

3. The library also includes functions to handle UTF-8 encoding and decoding.

  • stringToUTF8 allows you to encode a string to UTF-8 bytes, which you can then write to a stream or buffer.
  • stringFromUTF8 enables you to decode a buffer of UTF-8 bytes back into a string.
stringToUTF8("CSSScript", (byte: number) => {
  // console.log(byte)
});

4. It also allows you to convert between Uint8Array and Base64-URL.

// convert a Uint8Array to Base64-URL
let bytes: Uint8Array;
const result: string[] = [];
const state = { queue: 0, queuedBits: 0 };
const onChar = (char: string) => {
  result.push(char);
};
bytes.map((byte) => byteToBase64URL(byte, state, onChar));
// always call with `null` after processing all bytes
byteToBase64URL(null, state, onChar);
const string = result.join("");
// convert Base64-URL to a Uint8Array
const result: number[] = [];
const state = { queue: 0, queuedBits: 0 };
const onByte = (byte: number) => {
  result.push(byte);
};
for (let i = 0; i < string.length; i += 1) {
  byteFromBase64URL(string.charCodeAt(i), state, onByte);
}
const bytes = new Uint8Array(result);

Changelog:

09/17/2024

  • feat: add byteTo/FromBase64URL functions

You Might Be Interested In:


Leave a Reply