JavaScriptのnew URLで出る「Invalid URL」の直し方

​​JavaScript​Chromium,Node.js,トラブルシュート

new URL('/api/items?page=2') のように、/ で始まる相対パスだけを new URL() に渡すと、Node.js では TypeError: Invalid URL、Chromium では TypeError: Failed to construct 'URL': Invalid URL が出ます。相対パスは「どの URL から見た場所か」が決まらないと、完全な URL にならないためです。第2引数に基準の URL(base)を渡して new URL('/api/items?page=2', 'https://example.com') のようにすると、エラーは消えます。

API を呼ぶときに、パスにクエリパラメーターを付けて fetch() の URL を組み立てようとして、このエラーに出会うことがあります。Node.js と Chromium でエラーを起こし、出たメッセージと、直すと消えることを確かめました。

補足

検証環境は Ubuntu 24.04(x86_64)、Node.js 22.23.4、Chromium 153.0.8010.12(Playwright 1.63.0 で起動)です。ブラウザーで開くページは、Node.js の http モジュールで作ったサーバーから localhost:3000 で配りました。Firefox や Safari、Deno・Bun での文面と、Next.js などのフレームワークを通したときの動きは試していません。

base なしで相対パスを渡すとエラーになる

次のコードを invalid.mjs として保存し、Node.js で実行しました。

js
const url = new URL('/api/items?page=2');
console.log(url.href);

出力は次のとおりです(パスは例示用の値に置き換えています)。

text
$ node invalid.mjs
node:internal/url:818
      href = bindingUrl.parse(input, base, true);
                        ^

TypeError: Invalid URL
    at new URL (node:internal/url:818:25)
    at file:///path/to/app/invalid.mjs:1:13
    at ModuleJob.run (node:internal/modules/esm/module_job:343:25)
    at async onImport.tracePromise.__proto__ (node:internal/modules/esm/loader:681:26)
    at async asyncRunEntryPointWithESMLoader (node:internal/modules/run_main:117:5) {
  code: 'ERR_INVALID_URL',
  input: '/api/items?page=2'
}

Node.js v22.23.4

メッセージは Invalid URL だけですが、エラーには code: 'ERR_INVALID_URL' と、解釈できなかった文字列の input が付いています。Node.js のエラーの一覧にある ERR_INVALID_URL の説明にも、このエラーには、解釈に失敗した URL を入れた input が付くことが多いとあります。どの文字列で失敗したかは input を見ると分かります。スタックトレースの invalid.mjs:1 が、new URL() を呼んだ行です。

同じコードを <script> に書いたページを Chromium で開き、ページで投げられた例外を Playwright で受け取ると、次のとおりでした。

text
Uncaught TypeError: Failed to construct 'URL': Invalid URL

渡した文字列から URL を作れなかった、という意味です。try / catch で受け取ると、e.name は TypeError、e.message は Failed to construct 'URL': Invalid URL でした。

MDN の URL() コンストラクターのページには、base を渡さないと undefined として扱われ、URL(相対パスなら base と合わせたもの)が正しい URL にならないときは TypeError を投げるとあります。同じページの例でも、new URL("/en-US/docs") はエラーになっています。

第2引数に base を渡して直す

new URL() の第2引数に、相対パスの基準になる URL を渡します。

js
const url = new URL('/api/items?page=2', 'https://example.com');
console.log(url.href);
console.log(url.pathname, url.searchParams.get('page'));
text
$ node fix-base.mjs
https://example.com/api/items?page=2
/api/items 2

エラーは出ず、完全な URL ができました。pathname や searchParams も、ふつうの URL と同じように使えます。

ブラウザーでは、今のページの URL を base にする

ブラウザーで、表示しているページと同じサーバーの API を指したいときは、location.href か location.origin を base にします。http://localhost:3000/docs/fixed.html のページで、次のコードを実行しました。

js
console.log(new URL('/api/items?page=2', location.href).href);
console.log(new URL('/api/items?page=2', location.origin).href);
console.log(new URL('/api/items?page=2', document.baseURI).href);
console.log(new URL('api/items', location.href).href);
text
http://localhost:3000/api/items?page=2
http://localhost:3000/api/items?page=2
http://localhost:3000/api/items?page=2
http://localhost:3000/docs/api/items

/ で始まるパスは、どれを base にしてもサーバーの直下からの場所になりました。最後の行のように / を付けずに api/items と書くと、今のページがある /docs/ から見た場所になります。

base の末尾のスラッシュで、結果が変わる

base を渡せばエラーは消えますが、できる URL が思ったものと違うことがあります。base を https://example.com/api のようにパスまで含めて書いたときです。

js
console.log(new URL('items', 'https://example.com/api').href);
console.log(new URL('items', 'https://example.com/api/').href);
console.log(new URL('/items', 'https://example.com/api/').href);
console.log(new URL('./items', 'https://example.com/api/v1/users').href);
console.log(new URL('https://cdn.example.net/a.png', 'https://example.com/api/').href);
text
$ node base-path.mjs
https://example.com/items
https://example.com/api/items
https://example.com/items
https://example.com/api/v1/items
https://cdn.example.net/a.png

結果を並べると、次のようになりました。

  • base の末尾に / がないと、api は置き換えられ、https://example.com/items になる
  • base の末尾に / があると、api/ の下に付いて https://example.com/api/items になる
  • 渡すパスが / で始まると、base のパスは使われず、https://example.com/items になる
  • 渡す文字列が https:// から始まる完全な URL なら、base は使われない

MDN の URL() コンストラクターのページにも、base と相対パスは単純につなげるのではなく、base の最後の / までを今いる場所として扱い、/ で始まるパスは base のオリジンから見た場所になると書かれています。

ポイント

https://example.com/api/ のように、パスまで含めた base の下に付けたいときは、base の末尾を / で終え、渡すパスは / で始めないようにします。

base そのものが正しくなくても、同じエラーになる

base を渡しているのに Invalid URL が出るときは、base の中身を確かめます。次のコードは、環境変数 API_BASE を base にしています。

js
const base = process.env.API_BASE;
try {
  const url = new URL('/api/items', base);
  console.log(url.href);
} catch (e) {
  console.log(e.name, e.code, e.message);
  console.log('input:', e.input, '/ base:', e.base);
}

API_BASE をスキームのない example.com にした場合と、設定し忘れた場合、https://example.com にした場合で実行しました。

text
$ API_BASE=example.com node base-invalid.mjs
TypeError ERR_INVALID_URL Invalid URL
input: /api/items / base: example.com

$ node base-invalid.mjs
TypeError ERR_INVALID_URL Invalid URL
input: /api/items / base: undefined

$ API_BASE=https://example.com node base-invalid.mjs
https://example.com/api/items

base が example.com でも、環境変数が空で undefined になっても、base なしのときと同じ Invalid URL になりました。Node.js では、エラーの base に渡した base が入っていたので、input と合わせて表示すると原因を見つけやすくなります。https:// を付けた値にすると、エラーは消えました。Node.js の new URL() の説明にも、input と base のどちらかが正しい URL でないと TypeError を投げるとあります。

スキームのない文字列を base なしで渡したときも、結果を確かめました。

text
$ node no-scheme.mjs
example.com/api/items => TypeError ERR_INVALID_URL Invalid URL
//example.com/api/items => TypeError ERR_INVALID_URL Invalid URL
localhost:3000/api/items => localhost:3000/api/items protocol: localhost: host: ""
http://localhost:3000/api/items => http://localhost:3000/api/items protocol: http: host: "localhost:3000"

example.com/api/items と //example.com/api/items はエラーになりました。一方、localhost:3000/api/items はエラーにならず、localhost: がスキーム(protocol)として扱われ、host は空になりました。この URL を Node.js の fetch() に渡すと、TypeError: fetch failed(原因は unknown scheme)になり、localhost:3000 には届きませんでした。new URL() の時点ではエラーが出ないので、見落としやすいところです。base にする値は http:// か https:// から書きます。

失敗してもエラーにしたくないときは URL.canParse() と URL.parse()

ユーザーが入力した URL のように、正しくないかもしれない文字列を扱うときは、try / catch の代わりに URL.canParse() か URL.parse() を使えます。

js
console.log(URL.canParse('/api/items'));
console.log(URL.canParse('/api/items', 'https://example.com'));
console.log(URL.parse('/api/items'));
console.log(URL.parse('/api/items', 'https://example.com')?.href);
text
$ node canparse.mjs
false
true
null
https://example.com/api/items

URL.canParse() は URL にできるかどうかを true と false で返し、URL.parse() は URL にできないときに、エラーを投げずに null を返しました。Chromium でも、base を location.href にして、同じく false、true、null、URL の順になりました。Node.js の URL.parse() の説明とURL.canParse() の説明によると、URL.parse() は Node.js 22.1.0 で、URL.canParse() は 19.9.0 と 18.17.0 で加わったので、それより古い Node.js では使えません。ブラウザーでの使い方は、MDN の URL.parse() のページにあります。

URL.parse() で null が返ったときも、原因は new URL() と同じで、相対パスに base がないか、base が正しい URL になっていないかのどちらかです。

​Posted by 86