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:
- We add
thismessage:/
to our relative path. - We parse it using the URL constructor.
- We do whatever we need to do with the URL object.
- 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
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"
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)