← Debugging Guides

阅读中文版本

Node.js — TypeError: Failed to parse URL from /api

Fix relative URL errors in Node fetch by resolving URLs against a base, since server-side fetch has no document origin.

beginnerdebuggingnodefetch

Symptoms

  • TypeError: Failed to parse URL from /api/users
  • Code that works in the browser fails on the server
  • fetch receives only a path starting with a slash
  • A config value holds a path but no host

Possible causes

  • Node fetch requires an absolute URL and has no implicit document base
  • A front-end style relative path is reused on the server
  • An environment variable holds only a path without scheme and host
  • A router prefix is passed without the origin

Diagnosis steps

Confirm the URL is relative

node -e "fetch('/api').catch(e=>console.log(e.constructor.name, e.message))"

Interpretation

Node rejects a relative URL with a parse error, unlike a browser which resolves it against the page.

Resolve against an explicit base

node -e "new URL('/api', 'https://example.com').href"

Interpretation

Using the URL constructor with a base produces a valid absolute URL.

Check environment configuration

grep -rn "API_BASE\|BASE_URL" src

Interpretation

A base that contains only a path explains why requests never had an origin.

Root cause

Node fetch needs an absolute URL because there is no document to resolve a relative path against. Passing a path like /api is a browser assumption that does not hold on the server.

Fix

Build absolute URLs by resolving paths against a configured origin, or provide a base URL from configuration, so all server-side requests carry scheme and host.

Verify the fix

Run the request again and confirm it reaches the intended host, and check logs or the client to confirm the resolved URL is correct.

Symptom walkthrough

Server-side fetch throws TypeError: Failed to parse URL from /api/users, while the same code runs in a browser. The browser resolves the relative path against the page origin, but Node has no document origin, so a path alone is not a valid URL. The mistake is a front-end habit reused on the server, and it often hides behind a base URL that contains only a path.

Fix in practice

Construct absolute URLs by resolving paths against a configured origin with the URL constructor, and make the base URL include scheme and host. Centralizing this in one HTTP helper prevents individual call sites from repeating the mistake.

Verification

Run the request again and confirm it reaches the intended host, then verify the resolved URL in logs or the client. A correct absolute URL with a successful response confirms the fix.

Diagnostic commands

Check the behavior with commands like these:

node -e "fetch('/api').catch(e=>console.log(e.constructor.name, e.message))"
node -e "new URL('/api', 'https://example.com').href"
grep -rn "API_BASE\|BASE_URL" src