Base64URL Encode and Decode Helpers

Encode strings or bytes to unpadded base64url and decode back with strict alphabet, length and fatal UTF-8 validation.

JavascriptAuth Jwt

Code

javascriptsnippet
29 lines
export function encodeBase64Url(input) {
  const bytes = toBytes(input);
  let binary = "";
  for (const byte of bytes) binary += String.fromCharCode(byte);
  return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
}

export function decodeBase64Url(input, options = {}) {
  if (typeof input !== "string") throw new TypeError("input must be a string");
  if (!/^[A-Za-z0-9_-]*$/.test(input)) throw new Error("input contains invalid base64url characters");
  if (input.length % 4 === 1) throw new Error("input has an invalid base64url length");
  const { encoding = "utf-8" } = options;
  const padded =
    input.replace(/-/g, "+").replace(/_/g, "/") + "=".repeat((4 - (input.length % 4)) % 4);
  const binary = atob(padded);
  const bytes = Uint8Array.from(binary, (character) => character.charCodeAt(0));
  return new TextDecoder(encoding, { fatal: true }).decode(bytes);
}

function toBytes(input) {
  if (typeof input === "string") return new TextEncoder().encode(input);
  if (input instanceof Uint8Array) return input;
  throw new TypeError("input must be a string or Uint8Array");
}

const token = encodeBase64Url("user:42");
console.log(token);
console.log(decodeBase64Url(token));
console.log(encodeBase64Url(new Uint8Array([251, 255, 190])));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

dXNlcjo0Mg
user:42
-_--

How the snippet works

Count the functions encodeBase64Url, decodeBase64Url and toBytes as the entire surface area of Base64URL Encode and Decode Helpers.

for (const byte of bytes) binary += String.fromCharCode(byte); is the loop that carries the per-item work. Failure is loud: TypeError and Error aborts the current operation instead of degrading it.

Returns a newly built value, leaving the inputs as they were.

What to watch for

  • The guard typeof input !== "string" short-circuits the flow with an early throw when its condition holds.

Applying it

Signature: export function encodeBase64Url(input)

Import encodeBase64Url from the file and call it — the rest of the code is implementation detail.

Statements that matter

if (!/^[A-Za-z0-9_-]*$/.test(input)) throw new Error("input contains invalid base64url characters");
if (input.length % 4 === 1) throw new Error("input has an invalid base64url length");
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");

Interactive Tools for This Topic

FAQ

Does `encodeBase64Url` modify its input?
No. Nothing passed in is written to, which makes the call safe on shared data.
How does the snippet fail?
Validation comes first — `TypeError` and `Error` marks the failure at `typeof input !== "string"`, before any partial work happens.
Is the dependency story complicated?
Not at all: zero dependencies, so there is nothing to version or audit. The file defines `encodeBase64Url`, `decodeBase64Url`, `toBytes` at load time.