Skip to content

Menu

Encodings Cheat Sheet: Base64, base64url, URL Encoding, HTML Entities and Hex

Checked against Text and binary encodings RFC 4648, RFC 3986, WHATWG URL and HTML standards; examples run on Node 24.4.0 and Python 3.12.8 on 28 November 2026. Each section links to the official docs it was checked against.

This sheet is for developers who need to put bytes or text somewhere they don't fit as-is: binary in JSON, user input in a URL, or text in HTML. It covers Base64 and base64url from RFC 4648, percent-encoding from RFC 3986 and the WHATWG URL standard, HTML character references, and hex. Every Node and Python call below was run on Node 24.4.0 and Python 3.12.8, and the outputs shown are what they printed.

When to use what

Pick the encoding by where the data is going, not by habit. None of these is encryption; anyone can reverse them.

  • Binary in a text channel (JSON field, email, data URL): standard Base64.
  • Binary in a URL, filename or JWT: base64url, which swaps + and / for - and _. Most uses drop the = padding too.
  • A value inside a URL (query parameter, path segment): percent-encode it with encodeURIComponent() in JavaScript or quote(value, safe='') in Python. Better still, build URLs with URL and URLSearchParams and let them encode for you.
  • Text inside HTML: escape &, <, > and quotes, using your template engine's escaping rather than hand-rolled string replaces.
  • Bytes for a human to read (hashes, keys, packet dumps): hex. It doubles the size, where Base64 adds about a third, but it is easy to compare by eye.

The trap is layering: a value goes into JSON, then a URL, then HTML, and somebody encodes it twice or decodes at the wrong step. Encode once, at the boundary where the value enters each format. To try values quickly, use the Base64 encoder, the URL encoder, the HTML entity encoder and the URL parser. The encoding guide and the Base64 explainer give more background.

Standard Base64 uses A-Z a-z 0-9 + / and pads with =. base64url (RFC 4648 section 5) replaces + with - and / with _. Output from our run for the string café & crème/🙂? is shown below.

Buffer.from(s).toString('base64')

Node: UTF-8 bytes to standard Base64, giving Y2Fmw6kgJiBjcsOobWUv8J+Zgj8=

Buffer.from(s).toString('base64url')

Node: base64url with no padding (...8J-Zgj8); supported since v15.7.0

Buffer.from(b64, 'base64')

Node: decode; accepts both alphabets and ignores whitespace

btoa('café')

Browser and Node legacy API: works on Latin-1 text only; our emoji string threw InvalidCharacterError

bytes.toBase64({ alphabet: 'base64url', omitPadding: true })

Modern browsers: encode a Uint8Array directly; not in Node 24.4.0

From the docs, not run by us
base64.b64encode(data)

Python: bytes in, Base64 bytes out; encode strings to UTF-8 first

base64.urlsafe_b64encode(data).rstrip(b'=')

Python: base64url without padding, as JWTs use

base64.urlsafe_b64decode(s + b'=' * (-len(s) % 4))

Python before 3.15: add the padding back before decoding, or it raises Incorrect padding

encodeURI is described at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI. RFC 3986 section 2.2 lists the reserved characters: : / ? # [ ] @ ! $ & ' ( ) * + , ; =.

encodeURIComponent(value)

Encode one query value or path segment; leaves only A-Z a-z 0-9 - _ . ! ~ * ' ( )

encodeURI(url)

Encode a whole URL but keep ; / ? : @ & = + $ , #; a stray & inside a value will break the query

encodeURIComponent(s).replace(/[!'()*]/g, c => '%' + c.charCodeAt(0).toString(16).toUpperCase())

Strict RFC 3986 encoding, since encodeURIComponent leaves !'()* alone (MDN's helper)

new URLSearchParams({ q: 'a b&c=d' }).toString()

Form-style encoding: space becomes +, giving q=a+b%26c%3Dd

url.searchParams.set('q', 'tea & cake')

Set a parameter on a URL object and let it encode; produced ?q=tea+%26+cake

decodeURIComponent('a+b%20c')

Decodes %20 but leaves + as a plus (a+b c); use URLSearchParams to read form data

encodeURIComponent(String.fromCharCode(0xD800))

A lone surrogate throws URIError: URI malformed; clean it with toWellFormed() first

The WHATWG URL standard (https://url.spec.whatwg.org/) defines the form-urlencoded set: only ASCII alphanumerics and * - . _ stay as they are, and space becomes +.

quote('a b/c&d')

Path-style: safe='/' by default, so you get a%20b/c%26d

quote('a b/c&d', safe='')

Encode a single segment or value, slashes included: a%20b%2Fc%26d

quote_plus('a b/c&d')

Form-style: space to + and / to %2F, giving a+b%2Fc%26d

urlencode({'q': 'a b/c', 'e': 'é'})

Build a query string; uses quote_plus, so q=a+b%2Fc&e=%C3%A9

unquote('a+b%20c') # vs unquote_plus(...)

unquote keeps + (a+b c); unquote_plus turns it into a space (a b c)

The HTML standard has three forms: named (&amp;), decimal (&#169;) and hex (&#xA9;), all ending in ;. In normal text you must escape < and any & that would look like a reference; inside a quoted attribute you must also escape the quote character you used.

&amp; &lt; &gt; &quot; &#x27;

The five references you need for text and quoted attributes

&#169; &#xA9; &copy;

Decimal, hex and named forms of the same character; html.unescape turned all three into ©

html.escape(s)

Python: escapes & < > " ', safe for text and quoted attribute values

html.escape(s, quote=False)

Python: leaves quotes alone; fine for element text, not for attributes

html.unescape('&amp;amp;')

Decodes one level only, giving &amp;; a sign the value was escaped twice

RFC 4648 section 8 defines Base16 as case-insensitive with no padding. Python's base64.b16decode still accepts only uppercase unless you pass casefold=True (https://docs.python.org/3/library/base64.html).

Buffer.from('hi🙂').toString('hex')

Node: bytes to lowercase hex, 6869f09f9982; the emoji is four UTF-8 bytes

Buffer.from('68699f', 'hex')

Node: hex to bytes; decoding stops at the first non-hex character and drops an odd final digit

'hi'.encode().hex() / bytes.fromhex('68 69')

Python: bytes to hex and back; fromhex skips spaces

base64.b16encode(data)

Python: uppercase hex as bytes (b'6869F09F9982')

Worked example: Put a binary token in a URL and read it back

You need to pass a binary token (two bytes here, to keep the output short) in a link and in a query string from both Node and Python. Use base64url so the token needs no further escaping, and let the URL API build the query:

const token = Buffer.from([0xfb, 0xff]).toString('base64url');
const u = new URL('https://example.com/verify');
u.searchParams.set('t', token);
u.searchParams.set('next', '/a b?x=1');
console.log(Buffer.from([0xfb, 0xff]).toString('base64'), token);
console.log(u.href);
+/8= -_8
https://example.com/verify?t=-_8&next=%2Fa+b%3Fx%3D1

The same two bytes are +/8= in standard Base64. Put that in a query string unencoded and the + arrives as a space and the / and = confuse parsers. The base64url form -_8 uses only unreserved characters, so it passes through untouched. The next value had a slash, a space and a ?, and URLSearchParams encoded all three, with the space as +.

On the Python 3.12 side, urlsafe_b64decode(b'-_8') fails with Incorrect padding. Pad it first: s + b'=' * (-len(s) % 4) gives -_8=, which decodes to b'\xfb\xff'. Read the query with parse_qs or unquote_plus, not unquote, so + turns back into a space.

Common mistakes

  • Treating Base64 as a way to hide secrets.

    It is a reversible encoding with no key. Encrypt or hash the data if it must stay private, and only then Base64 it for transport.

  • Using encodeURI on a query value such as a&b=c.

    encodeURI keeps & and =, so the value splits into extra parameters. Use encodeURIComponent per value, or URLSearchParams.

  • Calling btoa() on text with non-Latin-1 characters.

    It throws InvalidCharacterError. Encode to UTF-8 bytes first (TextEncoder, or Buffer in Node) and Base64 the bytes.

  • Encoding a URL that is already encoded.

    %20 turns into %2520, which we saw from encodeURIComponent run twice. RFC 3986 says not to encode or decode the same string more than once; encode raw parts once when you build the URL.

  • Decoding form data with decodeURIComponent or Python's unquote.

    Both leave + as a plus. Use URLSearchParams in JavaScript, or unquote_plus and parse_qs in Python, for application/x-www-form-urlencoded data.

  • Using html.escape(s, quote=False) for attribute values.

    A quote in the value ends the attribute early and opens an XSS hole. Keep the default quote=True for attributes, or let your template engine escape.

  • Sending base64url with padding stripped to a decoder that expects it.

    Python before 3.15 and many other libraries reject unpadded input. Add = until the length is a multiple of 4 before decoding.