TypeError: Failed to parse URL when a Next.js server fetches its own API
TypeError: Failed to parse URL from /api/testShort answer
Server code has no page address, so fetch('/api/test') cannot be turned into a full URL and throws Failed to parse URL. Give fetch an absolute URL, make sure the variable that builds it is not undefined, or skip the HTTP call and run the same logic directly from the Server Component.
Fix it fast
1Find out which cause you have
Print the exact string passed to fetch. The text after 'from' in the error is that string, and its shape decides the cause.
grep -rnE "fetch\(" app lib pages | grep -v node_modules2Match what you see, then jump to its fix
- 1
The error says Failed to parse URL from /api/test, a bare pathA path without a host is used in server codeFix - 2
The error shows undefined/api/test, or the host part is missingThe environment variable that holds the base URL is emptyFix - 3
The page fetches /api/... from the same appA Server Component calls its own API routeFix
- 1
What does the error look like?
TypeError: Failed to parse URL from /api/testTypeError: Failed to parse URL from undefined/api/test
Cause 1 of 3
A path without a host is used in server code
1Check
A relative reference only resolves in the browser, against the page address. Without a base, the URL parser throws a TypeError.
node -e "try { new URL('/api/test') } catch (e) { console.log(e.name) }"2Fix
Build an absolute URL, or pass a base explicitly.
const url = new URL('/api/test', 'https://example.com')
const res = await fetch(url)3Verify
Reload the page; the server log no longer prints the error.
curl -I https://example.com/api/testConfirmed by developer.mozilla.org
Cause 2 of 3
The environment variable that holds the base URL is empty
1Check
A template string such as `${process.env.API_URL}/api/test` turns into undefined/api/test when the variable is absent. Next.js loads .env files at startup, so a new variable needs a restart, and a server-only variable is not visible to the browser unless it starts with NEXT_PUBLIC_.
grep -n "API_URL" .env .env.local 2>/dev/null2Fix
Define the variable in the right .env file, restart the server, and use NEXT_PUBLIC_ only where the browser needs it.
# .env.local
API_URL=http://localhost:30003Verify
Log the value once on the server after the restart.
node -e "console.log(require('fs').readFileSync('.env.local','utf8'))"Confirmed by nextjs.org
Cause 3 of 3
A Server Component calls its own API route
1Check
Server Components can read data directly, with fetch or a database client, so an HTTP hop to your own route only adds a URL that can be wrong.
grep -rn "/api/" app --include=page.tsx --include=page.js2Fix
Move the data logic into a shared function and call it from both the route handler and the Server Component.
// lib/items.ts
export async function getItems() {
return db.select().from(items)
}
// app/items/page.tsx
import { getItems } from '@/lib/items'
export default async function Page() {
const items = await getItems()
return <ul>{items.map(i => <li key={i.id}>{i.name}</li>)}</ul>
}3Verify
Reload the page; it renders without any request to your own /api route.
npm run devConfirmed by nextjs.org
How do I stop it coming back?
- Never write fetch('/api/...') in a Server Component, a route handler or a Server Action.
- Keep one base URL variable per environment and check it at startup.
- Share data functions between pages and route handlers instead of calling your own endpoints.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
Related fixes
Web apps
TypeError: fetch failed in a Next.js Server Component or route handler
TypeError: fetch failed
TypeError: fetch failed is a wrapper.
3 causes, each with a fixBack end
create-next-app keeps creating a TypeScript project
Would you like to use TypeScript? No / Yes
create-next-app now makes a TypeScript project by default.
2 causes, each with a fixBack end
Show a custom sign-in error in NextAuth without leaving the page
http://localhost:3000/api/auth/error?error=...
By default a failed NextAuth credentials sign-in navigates to the error page with the message in the URL.
3 causes, each with a fixBack end
Request body is rejected as too large in Next.js (1 MB default)
413 Payload Too Large
Next.js limits request bodies to 1 MB by default, in both Pages Router API routes and Server Actions.
3 causes, each with a fixBack end
Next.js server code cannot connect to its own API on 127.0.0.1
Error: connect ECONNREFUSED 127.0.0.1:3003
ECONNREFUSED means nothing was listening at that address and port when the server-side fetch ran.
2 causes, each with a fixBack end
next build stops with: Failed to collect page data for a route
Error: Failed to collect page data for /dashboard
Failed to collect page data for a route is the last line of a failed build, not the cause.
3 causes, each with a fix