next.js: "Fetch failed" error in production mode

Verify canary release

  • I verified that the issue exists in the latest Next.js canary release

Provide environment information

Operating System:
      Platform: win32
      Arch: x64
      Version: Windows 10 Pro
    Binaries:
      Node: 18.13.0
      npm: N/A
      Yarn: N/A
      pnpm: N/A
    Relevant packages:
      next: 13.4.2-canary.4
      eslint-config-next: 13.4.1
      react: 18.2.0
      react-dom: 18.2.0
      typescript: 5.0.4

Which area(s) of Next.js are affected? (leave empty if unsure)

Data fetching (gS(S)P, getInitialProps)

Link to the code that reproduces this issue

https://github.com/AlekseyMalakhov/check-next-fetch-error2

To Reproduce

  1. Download and install repository
  2. Run npm run dev
  3. Open http://localhost:3000/ in browser
  4. Click Add New Title button several times
  5. Wait for at least 8 seconds (while NextJS recreates an updated page)
  6. Click browser Refresh button 2 times
  7. You will see list of titles updated - New titles were added.
  8. Stop the dev server
  9. Run npm run build – during build time you will notice a fetch error.
  10. Run npm run start
  11. Open http://localhost:3000/ in browser
  12. Try to refresh browser window – you will see fetch errors in the server console.

Describe the Bug

Fetch API request works in development mode but fails with error in production. Here is an error

[Error: An error occurred in the Server Components render. The specific message is omitted in production builds to avoid leaking sensitive details. A digest property is included on this error instance which may provide additional details about the nature of the error.] {
  digest: '1327337937'
}
TypeError: fetch failed
    at Object.fetch (node:internal/deps/undici/undici:14062:11)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
  cause: Error: connect ECONNREFUSED ::1:3000
      at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1487:16)
      at TCPConnectWrap.callbackTrampoline (node:internal/async_hooks:130:17) {
    errno: -4078,
    code: 'ECONNREFUSED',
    syscall: 'connect',
    address: '::1',
    port: 3000
  }
}

Expected Behavior

No error is expected when browser window is refreshed.

Which browser are you using? (if relevant)

No response

How are you deploying your application? (if relevant)

No response

About this issue

  • Original URL
  • State: closed
  • Created a year ago
  • Reactions: 8
  • Comments: 40 (4 by maintainers)

Commits related to this issue

Most upvoted comments

Somebody with solution? When i try to deploy to production with docker i have same error. I am using local api in my server components with “fetch”.

`info Generating static pages (0/32)

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:80 at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1532:16) at TCPConnectWrap.callbackTrampoline (node:internal/async_hooks:130:17) { errno: -111, code: ‘ECONNREFUSED’, syscall: ‘connect’, address: ‘127.0.0.1’, port: 80 } }

Error occurred prerendering page “/”. 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 suppose that the problem was introduced in this commit (13.4.13-canary.0): 1398de9#diff-52cd95be25b76891bc705a2b498cbd25530283792dd37f6bbd332feb4255ab1fR25 – it replaced http.request() with fetch() call. Previous code had try/catch and was returning failed responses. Current code just awaits, so I guess that’s where the fetch throws.

Exactly, experiencing the same issue starting with 13.4.13 for Apollo client GraphQL requests in getServerSideProps. Downgrading to 13.4.12 resolved the issue for us. (lastest canary 13.4.14-canary.1 still affected)

main

I added export const runtime = "edge" to my page.tsx. it works.😆

Hi @timneutkens. Any movement on this? Similar to @b1rdex + @jthomaschewski, downgrading to 13.4.12 has temporarily resolved the issue, but would love to see a fix go in soon.

Please read my earlier reply on this issue: https://github.com/vercel/next.js/issues/49578#issuecomment-1639760485

No reproductions were shared still. Unless a reproduction is shared in follow-up comments this issue will be closed as it’s not constructive to keep spending time writing these replies when it’s clear no one is sharing a reproduction in the near future.

@zaunermax your case is exactly the case I’ve mentioned multiple times in this issue, you’re trying to fetch route handlers / api routes in components, you can’t do that, there is no server running during static generation. Instead you can read the data directly, using the same functions you’re using in the route handler / api route.

fyi @timneutkens - another person here who’s hitting the same issue as @b1rdex + @jthomaschewski with 13.4.13 (next start fine, fetch failed in standalone + Docker - deployed to AWS). Many thanks to @b1rdex for providing the repro. In my case the failure happens immediately when the favicon is requested, so not much fancy happening. CloudWatch log included in case that’s additionally helpful:

===

  • ready started server on ip-172-31-47-217.us-west-2.compute.internal:3000, url: http://ip-172-31-47-217.us-west-2.compute.internal:3000 – Listening on port 3000 url: http://ip-172-31-47-217.us-west-2.compute.internal:3000
  • error Failed to handle request for / TypeError: fetch failed at Object.fetch (node:internal/deps/undici/undici:11576:11) at process.processTicksAndRejections (node:internal/process/task_queues:95:5) at async invokeRequest (/usr/guzzle/ariadne/.next/standalone/node_modules/next/dist/server/lib/server-ipc/invoke-request.js:21:12) at async requestHandler (/usr/guzzle/ariadne/.next/standalone/node_modules/next/dist/server/lib/start-server.js:336:33) at async Server.<anonymous> (/usr/guzzle/ariadne/.next/standalone/node_modules/next/dist/server/lib/start-server.js:152:13) { cause: Error: connect ECONNREFUSED 127.0.0.1:46673 at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1495:16) { errno: -111, code: ‘ECONNREFUSED’, syscall: ‘connect’, address: ‘127.0.0.1’, port: 46673 } }
  • error Failed to handle request for /favicon.ico TypeError: fetch failed at Object.fetch (node:internal/deps/undici/undici:11576:11) at process.processTicksAndRejections (node:internal/process/task_queues:95:5) at async invokeRequest (/usr/guzzle/ariadne/.next/standalone/node_modules/next/dist/server/lib/server-ipc/invoke-request.js:21:12) at async requestHandler (/usr/guzzle/ariadne/.next/standalone/node_modules/next/dist/server/lib/start-server.js:336:33) at async Server.<anonymous> (/usr/guzzle/ariadne/.next/standalone/node_modules/next/dist/server/lib/start-server.js:152:13) { cause: Error: connect ECONNREFUSED 127.0.0.1:46673 at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1495:16) { errno: -111, code: ‘ECONNREFUSED’, syscall: ‘connect’, address: ‘127.0.0.1’, port: 46673 } }

Encountered this issue after upgrading from next@13.4.10 to next@13.4.13. Downgrading resolves the issue for me

@jthomaschewski I have the same problem – only standalone build errors in prod. Actually, 13.4.12 works fine for me, but not 13.4.13.

Encountered this issue after upgrading from next@13.4.10 to next@13.4.13. Downgrading resolves the issue for me.
I bundle my app with output: 'standalone' in a docker image.

next@13.4.13 works without issue when starting with next start after standard build (not standalone)

I’m experiencing the same issue, Im fetching an endpoint in my localhost server from a server component in next (Next 13.4.10), everything works like charm in my local environment. But then when I deploy it to Vercel the deployment works just fine, but then I navigate the App I get the following fetch error:

URL: http://127.0.0.1/AND_WHATEVER_API_ENDPOINT from my local server


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:80
      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: 80
  }
}

I wrapped the fetch call in a Try/Catch so that the App doesn’t break entirely, but no content is rendered at all, since the fetch call obviously will still fail.

All my client side fetching to the same URL works like charm in Vercel so its just serverside fetching. I have read a lot of different threads on this subject, tried a bunch of things like switching from localhost to 127.0.0.1 like it is now and nothing. Tried `export const dynamic = ‘force-dynamic’ , etc etc. No solution at all for the time being, very frustrating 😦

I think this problem may be due to:

The page requested a local API address during building, but this address has not been compiled yet, so there is no returned content. Sometimes, successful compilation may be due to obtaining the cache of dev mode during build


When testing the compiled website, I found that the page where generateStaticParameters was written cannot be accessed, and provided an Application error: a client side exception has occurred (see the browser console for more information). Digest: 2026204822 error, but the page that did not write generateStaticParams did not have such a problem

If the database operation is written in a component, the page content will no longer be cached, but some data (such as posts) do not need to be updated so frequently.

And at this point, the server component that uses fetch will still return an error in production mode

Error ```log 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 ::1:3000 at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1494:16) at TCPConnectWrap.callbackTrampoline (node:internal/async_hooks:130:17) { errno: -4078, code: 'ECONNREFUSED', syscall: 'connect', address: '::1', port: 3000 } } [Error: An error occurred in the Server Components render. The specific message is omitted in production builds to avoid leaking sensitive details. A digest property is included on this error instance which may provide additional details about the nature of the error.] { digest: '2026204822' } ```

Same, I encountered this error while building.

Error occurred prerendering page "/". 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)
info  - Generating static pages (40/40)

> Export encountered errors on following paths:
        /page: /
 ELIFECYCLE  Command failed with exit code 1.

It works normally in dev mode, unable to access all API addresses in production mode

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 ::1:3000
      at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1494:16)
      at TCPConnectWrap.callbackTrampoline (node:internal/async_hooks:130:17) {
    errno: -4078,
    code: 'ECONNREFUSED',
    syscall: 'connect',
    address: '::1',
    port: 3000
  }
}
[Error: An error occurred in the Server Components render. The specific message is omitted in production builds to avoid leaking sensitive details. A digest property is included on this error instance which may provide additional details about the nature of the error.] {
  digest: '2026204822'
}

using 13.3.0

this is my code ```typescript // Component const getItems = async () => { const res = await fetch('http://localhost:3000/api/item/latest?page=0', { next: { revalidate: 1800 } }) const items: ApiSuccessResponse<Item[]> = await res.json() return items.data }

const Component = async () => { const items = await getItems()

return (…) }


```typescript
// API
const items = itemsModel

export const GET = async () => {
  dbConnect()
  
  const itemsData: Item[] = await items.find({ valid: true })
    .sort({ time: 1 })
    .skip(page * 40)
    .limit(40)
  }

  return NextResponse.json(successResponse<Item[]>(itemsData))

I suppose that the problem was introduced in this commit (13.4.13-canary.0): https://github.com/vercel/next.js/commit/1398de9977b89c9c4717d26e213b52bc63ccbe7e#diff-52cd95be25b76891bc705a2b498cbd25530283792dd37f6bbd332feb4255ab1fR25 – it replaced http.request() with fetch() call. Previous code had try/catch and was returning failed responses. Current code just awaits, so I guess that’s where the fetch throws.

I am having the same issue. Works normally in localhost but when I deploy to production it crashes for some users. A refresh usually fixes the issue

I’m using 13.4.4 and is still happening

@Ruslanmsv Yes, I confirm - requests to https://jsonplaceholder.typicode.com/todos work good, but to http://localhost:3000 doesn’t

@AlekseyMalakhov I found this problem, that may be related. https://stackoverflow.com/questions/75607946/get-request-from-nextjs-13-2-3-gives-typeerror-fetch-failed-at-object-fetch

My guess is that it works in dev, but something is not configured to work with localhost in production build and you have to substitute localhost with some production URL.

and it’s easy to check with some toy API like https://jsonplaceholder.typicode.com/todos/1

I still think, it’s super weird, it’s not building with localhost

adding export const runtime = edge

fixes the problem 🤯🥲

This is likely fixed by #49638, can you verify that (npm install next@canary)?

No, it didn’t help. There is still the same error.