TypeError: fetch failed in a Next.js Server Component or route handler
TypeError: fetch failedShort answer
TypeError: fetch failed is a wrapper. The useful part is the cause attached to it. Log error.cause first. In server code it usually points to a relative URL that is not valid outside the browser, a localhost name that resolves to an address the server does not listen on, or a TLS certificate Node.js does not trust.
Fix it fast
1Find out which cause you have
Catch the error and print its cause. The message above it is generic; the cause tells the three reasons below apart.
try { await fetch(url) } catch (err) { console.error((err as Error).cause ?? err) }2Match what you see, then jump to its fix
- 1
The cause is about an invalid URL, and the call looks like fetch('/api/items')A relative URL is used in server codeFix - 2
The cause names localhost, and the same URL with 127.0.0.1 in place of localhost workslocalhost resolves to IPv6 but the other server listens on IPv4Fix - 3
The cause mentions a certificate, for example a self-signed or company-proxy certificateThe server uses a certificate Node.js does not trustFix
- 1
What does the error look like?
TypeError: fetch failed
Cause 1 of 3
A relative URL is used in server code
1Check
fetch() rejects with a TypeError when the URL is invalid. A path without a host is only valid in the browser, where it resolves against the page address. The server has no page address.
grep -rnE "fetch\(['\"`]/" app lib2Fix
Use an absolute URL built from an environment variable, or skip the HTTP hop and call the shared function the route handler uses.
const base = process.env.API_BASE_URL // e.g. https://api.example.com
const res = await fetch(`${base}/api/items`)3Verify
Reload the page and confirm the server log no longer shows the error.
curl -I "$API_BASE_URL/api/items"Confirmed by developer.mozilla.org
Cause 2 of 3
localhost resolves to IPv6 but the other server listens on IPv4
1Check
Since Node.js 17 dns.lookup returns addresses in the order the system gives them (verbatim), instead of IPv4 first. The name localhost can therefore reach a different address than the one the API is bound to.
node -e "require('dns').lookup('localhost',{all:true},(e,a)=>console.log(a))"2Fix
Write 127.0.0.1 in the URL. Or ask Node.js for IPv4 first at the top of your server entry or instrumentation file.
// Option 1: explicit address
const res = await fetch('http://127.0.0.1:4000/items')
// Option 2: IPv4 results first
import dns from 'node:dns'
dns.setDefaultResultOrder('ipv4first')3Verify
Run the same request again.
curl -I http://127.0.0.1:4000/itemsConfirmed by nodejs.org
Cause 3 of 3
The server uses a certificate Node.js does not trust
1Check
Node.js trusts a fixed set of well-known root CAs. A private CA is not among them, even when the browser or curl accepts it.
curl -v https://internal.example.com 2>&1 | grep -i "issuer\|verify"2Fix
Point NODE_EXTRA_CA_CERTS at a PEM file with your CA certificate before starting Next.js. Do not set NODE_TLS_REJECT_UNAUTHORIZED=0; Node.js documents it as turning certificate validation off and strongly discourages it.
NODE_EXTRA_CA_CERTS=/etc/ssl/my-company-ca.pem npm run start3Verify
Restart the server and repeat the request.
NODE_EXTRA_CA_CERTS=/etc/ssl/my-company-ca.pem node -e "fetch('https://internal.example.com').then(r=>console.log(r.status))"Confirmed by nodejs.org
How do I stop it coming back?
- Keep upstream base URLs in environment variables, never as relative paths in server code.
- Use 127.0.0.1 instead of localhost for services on the same machine.
- Log error.cause wherever a server-side fetch can fail.
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
Apollo Server rejects a request as a potential CSRF
HTTP 400 Bad Request from the GraphQL endpoint
Apollo Server's CSRF prevention is on by default.
3 causes, each with a fixWeb apps
Clerk cannot read its publishable key in a Next.js app
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY is undefined
Clerk reads NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY.
3 causes, each with a fixWeb apps
The shell cannot find create-next-app
command not found: create-next-app
create-next-app is not meant to be installed as a shell command.
2 causes, each with a fixWeb apps
ESLint fails with: Cannot find module 'next/babel'
ESLint stops on the first file with a Babel or parser error instead of listing lint results
next/babel is a Babel preset that ships inside the next package.
3 causes, each with a fixWeb apps
Firebase Auth says the API key is not valid
Firebase: Error (auth/api-key-not-valid.-please-pass-a-valid-api-key.)
The apiKey your app sends is either empty, wrong, or blocked.
4 causes, each with a fixWeb apps
Jest fails with SyntaxError: Unexpected token when testing a Next.js component
Jest failed to parse a file.
Jest only understands plain JavaScript until a transform and a few file mappings tell it more.
3 causes, each with a fix