DEV Community

Cover image for Dealing with relative paths in JavaScript URL parsing
Devin Weaver
Devin Weaver

Posted on

Dealing with relative paths in JavaScript URL parsing

Hey friends! πŸ‘‹ Let's talk about a neat trick for handling URLs in our apps, especially when dealing with relative paths.
You know, those paths that look like /app/route.

Here's the deal: The URL constructor in JavaScript usually needs a full URI, including the schema (like https:// or ftp://).
But, we often work with relative paths that don't have all that extra info.

Now, we could add a fake domain like https://example.com/ to make it work, but that feels a bit... well, fake! πŸ˜…

Here's where it gets interesting: There's this cool thing called the thismessage:/ schema. It's like a special code that tells the URL parser, "Hey, just focus on the path part, don't worry about domains and stuff." It's perfect for our relative paths!

The smart folks at W3C created this schema specifically for situations like ours. It's like a magic wand πŸͺ„ that lets us parse relative paths without any extra baggage.

Here's how we use it:

  1. We add thismessage:/ to our relative path.
  2. We parse it using the URL constructor.
  3. We do whatever we need to do with the URL object.
  4. When we're done, we can easily remove the thismessage: part to get back our original relative path.
const fullURI = 'https://example.com/app/route?query=params';
const relativeURI = '/app/route?query=params';

new URL(fullURI); // OK
new URL(relativeURI); // THROWS exception!

new URL(fullURI, 'thismessage:/'); // OK
new URL(relativeURI, 'thismessage:/'); // OK
Enter fullscreen mode Exit fullscreen mode

It's like putting on a special hat to get through a door, and then taking it off once we're inside! 🎩

And it is reversible in cases when you need to preserve the URI
but not the schema/hostname portions:

const url = new URL('thismessage:/app/route');

// will auto URL encode correctly
url.searchParams.set('query', someString);

url.href.substring(12); // => "/app/route?query=params"
Enter fullscreen mode Exit fullscreen mode

This approach is actually backed by some official internet rules (RFC2557 §5 & §12, for the curious cats out there 🐱). These rules say that when you can't resolve a relative URI any other way, you should treat it as if it started with thismessage:/.

There you have it! A friendly, standards-compliant way to work with relative paths in our URL handling. It's like having a Swiss Army knife for URLs – versatile and handy!

I hope this explanation makes the concept clearer and more fun to understand. Happy coding, everyone! πŸš€πŸ’»

Top comments (0)