Common Next.js errorsTypeError: Failed to parse URL from /api/...
TypeError: Failed to parse URL from /api/products (or fetch failed, ECONNREFUSED 127.0.0.1:3000) in a Server Component, a Server Action or generateMetadata. The server tried to fetch its own API with a relative address, or with localhost.
Why it happens
In the browser, /api/products is relative to the page's address. On the server there's no page address to be relative to. And during a build or on Vercel, nothing is listening on localhost:3000, so a hard-coded local address fails in production even though it worked on your laptop.
How to fix it
Don't call your own API from the server: call the function the API route uses. It's faster too, with no extra network trip.
lib/products.ts and app/shop/page.tsx // lib/products.ts
export async function listProducts() {
return db.product.findMany({ where: { published: true } })
}
// app/api/products/route.ts keeps serving the browser:
// return Response.json(await listProducts())
// app/shop/page.tsx (Server Component)
import { listProducts } from '@/lib/products'
export default async function Shop() {
const products = await listProducts()
// ...
}
If you must fetch over HTTP (another service, say), build a full URL from configuration, such as new URL('/api/products', process.env.API_BASE_URL), never from localhost.