Skip to content
Writing
Engineering
· · 2 min

The URL is a data structure

Package
listen to this article from the Wonder Why? podcast
Listen

In 2020, I published Urley, a small, dependency-free collection of utilities for working with URLs. It was about 885 bytes gzipped, supported multiple JavaScript environments and did a handful of fairly ordinary things.

Six years later, I'm considerably less interested in the utility itself than the thing it was manipulating.

A URL looks like a string. Treating it as one is where a surprising number of problems begin.

The wrong data structure

Consider the following query string:

const query = "tag=audio&sort=price&tag=electronics";

The natural inclination is to represent its contents as an object.

Object.fromEntries(new URLSearchParams(query));

// {
//   tag: "electronics",
//   sort: "price"
// }

We've successfully parsed the query and simultaneously destroyed some of its information.

A slightly more appropriate representation would be a :

{
  tag: ["audio", "electronics"],
  sort: ["price"]
}

But we've still lost the original ordering between keys.

The representation used by is conceptually closer to an ordered collection of tuples.

[
  ["tag", "audio"],
  ["sort", "price"],
  ["tag", "electronics"]
]
lost 1 pair
tag: "electronics"
sort: "price"
→ tag=electronics&sort=price
Not recommended: Object
order changed
tag: ["audio", "electronics"]
sort: ["price"]
→ tag=audio&tag=electronics&sort=price
Not recommended: Multimap
round-trips
["tag", "audio"]
["sort", "price"]
["tag", "electronics"]
→ tag=audio&sort=price&tag=electronics
Recommended: Ordered tuples
Edit the query. Each representation is turned back into a string; only one gives you back what you gave it.

The distinction matters when we expect a transformation to be reversible. Before writing a parser, we need to decide which properties of the input are worth preserving.

A more convenient data structure isn't necessarily a more correct one.

The order of operations

One of the utilities I included in Urley was a function for decoding URL components.

Decoding sounds relatively harmless until it happens at the wrong point in the parsing process.

const query = "q=rock%26roll&sort=recent";

Decoding the entire string before identifying its delimiters produces:

"q=rock&roll&sort=recent"

The encoded ampersand was part of a value. It has now become indistinguishable from the delimiter separating two parameters.

The correct order is to identify the structural boundaries first and decode the individual components afterwards.

3 parameters
the query
q=rock%26roll&sort=recent
decodeURIComponent(query)
q=rock&roll&sort=recent
new URLSearchParams(…)
q→rockroll→""sort→recent
Not recommended: Decode, then split
2 parameters
the query
q=rock%26roll&sort=recent
split at & and =
q=rock%26rollsort=recent
decode each key and value
q→rock&rollsort→recent
Recommended: Split, then decode each part
Pick an escape. Decoding first turns data into syntax; splitting first keeps it data.

This is particularly important because decoding is not generally .

decodeURIComponent("%252F"); // "%2F"
decodeURIComponent("%2F");   // "/"

Decoding something twice can change its meaning entirely.

Encoding isn't decoration applied to a string. It's part of the mechanism that distinguishes data from syntax.

Establishing equivalence

Urley also included utilities for normalising URLs and joining their constituent parts.

Normalisation is interesting because it requires us to define equivalence.

const a = "https://EXAMPLE.com:443/products";
const b = "https://example.com/products";

new URL(a).href === new URL(b).href;
// true

Both describe the same normalised URL.

But consider these:

const a = "/products?sort=price&sort=name";
const b = "/products?sort=name&sort=price";

Whether they're equivalent depends on the application consuming them.

A server might use the first parameter, the last parameter or interpret both as an ordered sequence of sorting instructions.

Canonicalisation without knowledge of those semantics can collapse two distinct requests into the same cache entry.

I'd therefore separate URL normalisation from application-specific identity.

function productCacheKey(url: URL) {
  const tags = url.searchParams.getAll("tag");

  return JSON.stringify([
    url.origin,
    url.pathname,
    [...new Set(tags)].sort(),
    url.searchParams.get("page") ?? "1"
  ]);
}

This deliberately treats tags as an unordered set and assumes these are the only parameters relevant to the resource.

That's an application contract, not a universal property of URLs.

The guarantees of a parser

One of the more interesting objectives in the is idempotency across parsing and serialisation.

Once a valid URL has been parsed and serialised, repeating that operation shouldn't continue changing its representation.

const normalize = (input: string) =>
  new URL(input).href;

normalize(normalize(input)) === normalize(input);

Notice that this doesn't require the normalised output to be textually identical to the original input.

normalize("https://EXAMPLE.com:443/a/../b");

// "https://example.com/b"

Information about the original spelling has disappeared, but the normalised representation is stable.

text changedstable
as typed
https://EXAMPLE.comlowercased:443default port/a/../bdot segments
new URL(input).href
https://example.com/b
new URL(new URL(input).href).href
https://example.com/b
Pick a URL or type one. Its spelling changes the first time it's parsed, and never again.

These days, I'd reach for the native before implementing most of Urley's functionality again. But I still find the underlying engineering problem rather interesting.

We persist application state in URLs, derive cache identities from them, navigate between resources with them and share them between entirely different computing environments.

For something we spend so much time passing around as a string, it's a remarkably consequential data structure.

— Adenekan

Thoughts on this one?

Tell me what it made you think, or where you think I got it wrong.

Still working on the last 10%.0:00pm in london