- One Tip a Week
- Posts
- One Tip a Week: JavaScript's URL and Slash
One Tip a Week: JavaScript's URL and Slash
This week’s tip of the week is the URL class in JavaScript.
I was already aware that URL is a better and more secure way to build URLs compared to string concatenation. In fact, my recent PR was mostly about cleaning up some vibe code in my dev.to MCP server by swapping in URL. 😅
What I only just discovered though while refactoring this code is how important the trailing slash is when your base URL has a path. Without it, relative paths resolve to the domain and drop your path entirely. I always assumed the base URL in the URL constructor was always literally the base URL and it just always stripped the path.
const base = new URL("https://dev.to/api"); // no trailing slash
const articles = new URL("articles", base);
console.log(articles.toString());
// https://dev.to/articles <-- dropped /api
const baseWithSlash = new URL("https://dev.to/api/"); // with trailing slash
const articles2 = new URL("articles", baseWithSlash);
console.log(articles2.toString());
// https://dev.to/api/articles ✅
So the lesson here: URL is the way to go instead of concatenating strings, and if your base URL includes a path, add that trailing slash so your relative URLs resolve as expected.
That’s it! Short and sweet. Until the next one!
Update 2025/11/24 afternoon: Thanks to @whiteshoulders.bsky.social on Bluesky for a small correction.
> That's not true, try it with an url with more than one segment in path and you'll see that without a trailing slash only the last segment is droped not the full path.
So TLDR last slash, if any is where it’s relative to.