next.jsvercel

TypeError: fetch failed during Next.js project build


I got this error during Vercel deployment:

TypeError: fetch failed
    at Object.fetch (node:internal/deps/undici/undici:11457:11)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
  cause: Error: connect ECONNREFUSED 127.0.0.1:3000
      at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1494:16)
      at TCPConnectWrap.callbackTrampoline (node:internal/async_hooks:130:17) {
    errno: -111,
    code: 'ECONNREFUSED',
    syscall: 'connect',
    address: '127.0.0.1',
    port: 3000
  }
}
Error occurred prerendering page "/match". Read more: https://nextjs.org/docs/messages/prerender-error
TypeError: fetch failed
    at Object.fetch (node:internal/deps/undici/undici:11457:11)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)

I guess probably is because of the http://localhost:3000/api/event, how can I replace a correct url to localhost?

async function getData(): Promise<Events[]> {
  const data = await fetch(`http://localhost:3000/api/event`, {
    cache: "no-cache",
  }).then((res) => res.json());
  return data;
}

Solution

  • This error occurs if you try to call your internal API route from a server component at build time, where there is no application running (the application being build and not deployed yet). Tim Neutkens from Next.js points that out on a GitHub issue with a similar error:

    This is because you're trying to fetch from an internal api route during build, which is not supported.

    Instead of calling the internal API route from a server component, which then calls your DB or CMS, reach them directly from the component. It helps avoid the error, and also an additional useless API call.


    That has been said, if the API is not your internal one, you can replace

    fetch('http://localhost:3000/api/event')
    

    with

    fetch(process.env.URL + '/api/even')
    

    and create an .env file in which you add:

    URL=http://localhost:3000
    

    Then on the Vercel dashboard, you set an URL environment variable with your production URL.