Search tools

Developer guides

Base64URL vs Base64: Fix atob() Failed InvalidCharacterError in JS

Browser atob() throws InvalidCharacterError on JWTs and OAuth tokens encoded with Base64URL. Learn why - and _ fail and decode UTF-8 payloads safely.

Warm ivory studio 3D editorial tiles showing an amber keycap embossed with plus and slash linked through clear glass to a teal keycap embossed with hyphen and underscore

You try to decode a JWT payload or OAuth verifier with atob(), and the browser immediately throws:

DOMException: Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded.

Here is the fast fix: JWTs, WebAuthn challenges, and OAuth tokens use Base64URL (RFC 4648 Section 5), not standard Base64. Native atob() expects +, /, and = padding, so replacing - with +, _ with /, and restoring trailing = characters solves the crash at once.

If you need to inspect or convert encoded strings immediately in your browser without writing a script, paste them into our Base64 encoder and decoder.

What is the difference between Base64 and Base64URL?

Standard Base64 uses +, /, and = characters that break URLs, filenames, and query strings without percent-encoding. Base64URL swaps those two punctuation symbols for - and _ and drops optional = padding.

Compare how the exact same UTF-8 text "café?" encodes in each alphabet:

Format Encoded string 62nd char 63rd char Padding Safe in atob()?
Standard Base64 Y2Fmw6k/ + / = kept Yes (ASCII only)
Base64URL Y2Fmw6k_ - _ Usually omitted Throws InvalidCharacterError

base64url-vs-base64-atob-failed-invalidcharactererror-diagram

Sometimes your atob() helper appears to work for months in testing, then crashes in production on one user token. That happens whenever a token payload happens not to contain byte indices 62 (_) or 63 (-), or lands cleanly on a 3-byte boundary with zero padding.

Why atob() corrupts emojis and accented characters too

Even after replacing - and _, atob("Y2Fmw6k/") returns "café?" instead of "café?"!

That happens because atob() treats every decoded byte as a single Latin-1 character code (0x00 to 0xFF) rather than multi-byte UTF-8 text. Decoding JWT user names containing accents, CJK characters, or emojis requires passing the bytes through TextDecoder.

How to decode Base64URL cleanly in JavaScript and Node.js

Always normalize - and _, restore missing = padding modulo 4, and convert binary bytes with TextDecoder.

In browsers and modern runtimes (Edge, Deno, Cloudflare Workers, Node 18+):

export function decodeBase64Url(input) {
  const base64 = input.replace(/-/g, "+").replace(/_/g, "/");
  const padLength = (4 - (base64.length % 4)) % 4;
  const padded = base64.padEnd(base64.length + padLength, "=");

  const binary = atob(padded);
  const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));
  return new TextDecoder().decode(bytes);
}

console.log(decodeBase64Url("Y2Fmw6k_")); // "café?"

In Node.js backend services, Buffer supports "base64url" directly since Node v16 without manual character replacements:

// Node.js 16+: handles '-', '_', omitted padding, and UTF-8 natively
const text = Buffer.from("Y2Fmw6k_", "base64url").toString("utf8");
console.log(text); // "café?"

How to encode Base64URL safely for APIs and PKCE

Going the other direction is just as error-prone when calling btoa(). Standard btoa() rejects UTF-8 characters above Latin-1 (0xFF) and outputs +, /, and = characters that break URL query parameters.

Encode UTF-8 bytes cleanly, then swap the three URL-unsafe characters:

export function encodeBase64Url(text) {
  const bytes = new TextEncoder().encode(text);
  const binary = Array.from(bytes, (b) => String.fromCharCode(b)).join("");
  return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
}

If you are trying to inspect raw claims from an ID or access token rather than hand-rolling a parser, split the middle dot segment safely or paste the full token into our JWT decoder in the browser.

Base64URL debugging FAQ

Why do some Base64 strings still fail atob() when there is no “-” or “_”?

Missing = padding or stray whitespace is usually the culprit. Check whether your string length is a multiple of 4, trim trailing newlines (\n), and remove data URI prefixes like data:image/png;base64, before calling atob().

Can Chrome’s newer Uint8Array.fromBase64() replace this helper?

Modern browsers are shipping native Uint8Array.fromBase64(str, { alphabet: "base64url" }). Check browser support targets before dropping the 5-line atob() + TextDecoder helper above for legacy Safari or older mobile WebViews.

Is Base64URL safe for passwords or API secrets?

No. Base64URL is purely an encoding format for safe transport in URLs and headers, not encryption. Anyone can decode it back to plain text in milliseconds.

Convert standard Base64, URL-safe Base64URL, and UTF-8 strings cleanly in the ToolQuilt Base64 tool.

Read next