Base64URL vs standard Base64: alphabet, padding and URL parsing

Recognize dash and underscore, understand optional padding, and avoid plus-to-space corruption in URL query parameters.

Base64URL changes two alphabet characters: standard Base64's plus becomes a dash, and slash becomes an underscore. The encoded information is unchanged. The variant helps when the surrounding protocol gives special meaning to plus or slash, but it does not exempt the value from every URL or application rule.

Use a vector that exposes the difference

The bytes FB FF encode as +/8= in standard Base64 and -_8= in Base64URL. A test such as Hello produces only shared alphabet characters, so it cannot reveal whether URL-safe conversion is working.

const standard = btoa(String.fromCharCode(251, 255));
const urlSafe = standard.replace(/\+/g, '-').replace(/\//g, '_');
console.log(standard); // +/8=
console.log(urlSafe); // -_8=

Padding is a separate agreement

Many token formats omit trailing equals signs, while other systems keep them. Changing the alphabet and removing padding are separate choices. An unpadded input with remainder two needs two equals signs for a padded representation; remainder three needs one. Remainder one cannot be repaired by padding alone because one six-bit character is insufficient to describe a full byte.

When validating, also check unused bits in the last character. A decoder that ignores them may accept several strings for the same byte sequence. That ambiguity can matter when an application compares encoded strings instead of decoded bytes. A canonical producer should emit one agreed representation.

Do not confuse query parsing with Base64 decoding

Form-style query parsing interprets a literal plus as a space. A standard Base64 value pasted unescaped into a query can therefore be corrupted before the decoder sees it. Construct the query with URLSearchParams, or use the Base64URL variant if the receiving protocol specifies it.

const query = new URLSearchParams({ payload: '+/8=' });
console.log(query.toString()); // payload=%2B%2F8%3D
console.log(query.get('payload')); // +/8=

Do not automatically replace every space with plus: a space might be genuine formatting or evidence of another error. Preserve the source, identify the transport layer that changed it, and apply a deliberate correction. For JWT segments, use the token format's Base64URL rules rather than inventing a general repair policy.

The standard and URL-safe alphabets are described in RFC 4648. Your integration still needs explicit choices for padding, whitespace acceptance and maximum length.