❯ehsan.blog
~/blog/one-leading-slash-deletes-half-your-api-base-url — zsh
❯cat one-leading-slash-deletes-half-your-api-base-url.md

One leading slash deletes half your API base URL

·8 min read

One leading slash deletes half your API base URL — article card for a post by Ehsan Shahid

Every fetch wrapper I have ever written starts the same way. You have a base URL, you have a path, you stick them together:

js
const res = await fetch(new URL(path, baseURL), { headers })

new URL() is the grown-up way to do it. No manual slash counting, no replace(/\/+$/, ""), it is built into the language. So I used it, my base URL was https://api.example.com/api/v1, I asked for /users, and the server answered 404.

The URL that actually went out was https://api.example.com/users. The /api/v1 part was gone.

That is not a bug in Node. new URL(path, base) is not joining two strings — it is doing what a browser does when it sees a link on a page. And links have rules that nobody reads until they cost them an afternoon.

The two rules that surprise everyone

Here is the whole thing in one short script. I ran it on Node v22.16.0, but these are the WHATWG URL rules, so browsers, Deno and Bun all agree.

js
const cases = [
  ["users",   "https://api.example.com/api/v1"],
  ["/users",  "https://api.example.com/api/v1"],
  ["users",   "https://api.example.com/api/v1/"],
  ["/users",  "https://api.example.com/api/v1/"],
  ["users",   "https://api.example.com/api/v1?key=abc"],
]

for (const [path, base] of cases) {
  console.log(
    `${JSON.stringify(path).padEnd(9)} + ${base.padEnd(38)} = ${new URL(path, base).href}`,
  )
}

The output:

plaintext
"users"   + https://api.example.com/api/v1         = https://api.example.com/api/users
"/users"  + https://api.example.com/api/v1         = https://api.example.com/users
"users"   + https://api.example.com/api/v1/        = https://api.example.com/api/v1/users
"/users"  + https://api.example.com/api/v1/        = https://api.example.com/users
"users"   + https://api.example.com/api/v1?key=abc = https://api.example.com/api/users

Read those five lines slowly, because only one of them is what you wanted.

Rule one: a leading slash throws away the whole base path. Lines two and four both land on /users. A path that starts with / means “from the root of the site”, exactly like an href="/about" on a web page. It does not care that your base URL had /api/v1 in it. Your version prefix, your /api mount point, your tenant segment — all deleted, silently, with a 200 or 404 from some other part of your server as the only clue.

Rule two: without a trailing slash, the last segment is replaced. Look at line one. The base ends in v1, and v1 disappeared. To the URL parser, https://api.example.com/api/v1 describes a file called v1 sitting in a folder called /api/. A relative path is resolved next to that file, not inside it. Add the trailing slash and v1 becomes a folder, which is what you meant all along (line three).

And line five is a small bonus: the query string on your base URL is gone too. If you were putting an API key there, it is not being sent.

So one missing character at the end of a config value, or one extra character at the start of a path, changes which endpoint you hit. Both look completely normal in a code review.

The version that leaks your token

The two rules above cost you a 404. This next one can cost you more.

Because new URL() resolves like a link, a path is allowed to stop being a path. If it starts with //, the part after it is a hostname. Not a folder on your server — a whole different server.

Watch what happens to the Authorization header when it does. Two throwaway servers, one pretending to be my API, one pretending to be someone else’s:

js
import http from "node:http"

const listen = (name) => {
  const s = http.createServer((req, res) => {
    console.log(`[${name}] got ${req.url} with ${req.headers.authorization}`)
    res.end("{}")
  })
  return new Promise((r) => s.listen(0, () => r([s, s.address().port])))
}

const [myApi, apiPort] = await listen("my-api")
const [someoneElse, theirPort] = await listen("someone-else")

const BASE = `http://127.0.0.1:${apiPort}/api/v1/`

async function call(path) {
  const url = new URL(path, BASE)
  console.log(`\ncalling ${JSON.stringify(path)} -> ${url.href}`)
  await fetch(url, { headers: { Authorization: "Bearer my-secret-token" } })
}

await call("users")
await call(`//127.0.0.1:${theirPort}/collect`)

myApi.close()
someoneElse.close()

And the output:

plaintext
calling "users" -> http://127.0.0.1:35035/api/v1/users
[my-api] got /api/v1/users with Bearer my-secret-token

calling "//127.0.0.1:44147/collect" -> http://127.0.0.1:44147/collect
[someone-else] got /collect with Bearer my-secret-token

The second server was never configured anywhere. It is not in my base URL, not in an allowlist, not in my code. A string that looked like a path pointed at it, and my client politely delivered a bearer token to it.

A full https://evil.com/collect does the same thing — when the first argument is already a complete URL, the base is ignored entirely.

“But I never write paths like that.” Probably true. The question is whether anything else ever does. Paths come from places you do not control more often than you think:

  • pagination, where you follow the next link straight out of a JSON response
  • a slug or ID from a route param that you drop into a template string
  • a path stored in a database, or in a feature flag, or in a CMS field
  • a shared constants file that somebody else edits

None of those need an attacker to be interesting. A bad value in a config table is enough to point authenticated requests at the wrong host.

The fix is nine lines

Do not hand new URL() anything you have not squeezed first. Two moves: force the base to end in a slash so nothing gets eaten, strip leading slashes off the path so it can never go up or sideways. Then check the result really is where you expected to land.

ts
export function joinUrl(base: string, path: string): URL {
  const root = new URL(base.endsWith("/") ? base : base + "/")
  const url = new URL(path.replace(/^\/+/, ""), root)

  if (url.origin !== root.origin || !url.pathname.startsWith(root.pathname)) {
    throw new Error(`path "${path}" escapes the base URL ${root.href}`)
  }
  return url
}

Three small things worth saying out loud about those nine lines.

base.endsWith("/") is what kills rule two. It costs one character and it means your teammate can write the base URL either way in .env and get the same requests.

path.replace(/^\/+/, "") is what kills rule one — and it handles //evil.com too, but not by blocking it. Strip the slashes and //evil.com/collect becomes the perfectly boring relative path evil.com/collect, which resolves to https://api.example.com/api/v1/evil.com/collect. It stays on your server. It will 404, and a 404 is a much better outcome than a leaked token.

The if is for everything the stripping does not catch: a full https://evil.com/..., which ignores the base, and ../../admin, which stays on the right host but climbs out of your API prefix. Comparing origin catches the first. Comparing pathname catches the second — and it works because new URL() has already resolved the .. segments by the time you look, so there is nothing left to trick you with.

Prove it, then trust it

This is small enough that the test is shorter than the explanation, so there is no excuse not to have one. No framework, just node assert.mjs:

js
import assert from "node:assert/strict"
import { joinUrl } from "./join-url.js"

const BASE = "https://api.example.com/api/v1" // note: no trailing slash
const ok = (p, want) => assert.equal(joinUrl(BASE, p).href, want, p)
const blocked = (p) => assert.throws(() => joinUrl(BASE, p), /escapes/, p)

ok("users", "https://api.example.com/api/v1/users")
ok("/users", "https://api.example.com/api/v1/users")
ok("users/42", "https://api.example.com/api/v1/users/42")
ok("users?page=2", "https://api.example.com/api/v1/users?page=2")

// neutralised, not blocked: it becomes an ordinary segment on your own host
ok("//evil.com/steal", "https://api.example.com/api/v1/evil.com/steal")

blocked("https://evil.com/steal")
blocked("../../admin")
blocked("users/../../../admin")

// the base works the same with or without its trailing slash
assert.equal(
  joinUrl("https://api.example.com/api/v1/", "users").href,
  "https://api.example.com/api/v1/users",
)

console.log("all assertions passed")

That prints all assertions passed. Those are the nine cases that actually decide whether your client sends requests where you think it does.

What about just adding the strings?

You might be tempted to skip new URL() and write base + "/" + path. It does avoid all of the above, and it hands you a different problem: /users now gives you https://api.example.com/api/v1//users. Whether that doubled slash matches your route is up to your server and your router — it is not the same string as /users, so it is not guaranteed to be the same route. You end up normalising slashes by hand, which is the job new URL() was already doing correctly. Keep the parser. Just stop feeding it raw input.

The short version

  • new URL(path, base) resolves like a link in a web page, not like a path join.
  • A leading / on the path deletes the base path. Strip it.
  • A base URL without a trailing / loses its last segment. Add it.
  • A path is allowed to become a different host. Check origin and pathname before you attach credentials.

The whole fix is one small function you write once and never think about again. The bug it prevents is the kind you only notice when a 404 shows up in production, or when a token shows up in somebody else’s logs.

The query string half of the same URL has its own version of this problem: your query string says page=undefined covers why a missing filter arrives as the literal word, and why the obvious one-line fix then deletes page=0.

❯ls ./related
❯cat ./comments

Comments are not configured yet. Enable GitHub Discussions and paste the giscus repo-id / category-id into src/consts.ts.