Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

"Fetch failed" error in production mode #49578

Closed
1 task done
AlekseyMalakhov opened this issue May 10, 2023 · 40 comments · Fixed by #53131
Closed
1 task done

"Fetch failed" error in production mode #49578

AlekseyMalakhov opened this issue May 10, 2023 · 40 comments · Fixed by #53131
Labels
bug Issue was opened via the bug report template. Pages Router Related to Pages Router.

Comments

@AlekseyMalakhov
Copy link

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

@AlekseyMalakhov AlekseyMalakhov added the bug Issue was opened via the bug report template. label May 10, 2023
@github-actions github-actions bot added the Pages Router Related to Pages Router. label May 10, 2023
@timneutkens
Copy link
Member

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

@AlekseyMalakhov
Copy link
Author

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.

@Ruslanmsv
Copy link

Ruslanmsv commented May 15, 2023

Same here for 13.4.3-canary.0 , I get the following error with pnpm build:

TypeError: fetch failed
❯ pnpm build

> approuter-2@0.1.0 build /Users/ruslanmsv/Developer/Nextjs/approuter-2
> next build


warn - No utility classes were detected in your source files. If this is unexpected, double-check the `content` option in your Tailwind CSS configuration.
warn - https://tailwindcss.com/docs/content-configuration
- info Creating an optimized production build  
- info Compiled successfully
- info Linting and checking validity of types  
- info Collecting page data  
[    ] - info Generating static pages (0/5)
SERVER RUN
TypeError: fetch failed
    at Object.fetch (node:internal/deps/undici/undici:11522:11)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
  cause: AggregateError
      at internalConnectMultiple (node:net:1103:18)
      at afterConnectMultiple (node:net:1616:5)
      at TCPConnectWrap.callbackTrampoline (node:internal/async_hooks:130:17) {
    code: 'ECONNREFUSED',
    [errors]: [ [Error], [Error] ]
  }
}

Error occurred prerendering page "/". Read more: https://nextjs.org/docs/messages/prerender-error
TypeError: fetch failed
    at Object.fetch (node:internal/deps/undici/undici:11522:11)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
- info Generating static pages (5/5)

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

except that I can not start an app with pnpm start because of

Error: Cannot find module '/Users/ruslanmsv/Developer/Nextjs/approuter-2/.next/prerender-manifest.json'
❯ pnpm start

> approuter-2@0.1.0 start /Users/ruslanmsv/Developer/Nextjs/approuter-2
> next start

- ready started server on 0.0.0.0:3000, url: http://localhost:3000
Error: Cannot find module '/Users/ruslanmsv/Developer/Nextjs/approuter-2/.next/prerender-manifest.json'
Require stack:
- /Users/ruslanmsv/Developer/Nextjs/approuter-2/node_modules/.pnpm/next@13.4.3-canary.0_react-dom@18.2.0_react@18.2.0/node_modules/next/dist/server/next-server.js
- /Users/ruslanmsv/Developer/Nextjs/approuter-2/node_modules/.pnpm/next@13.4.3-canary.0_react-dom@18.2.0_react@18.2.0/node_modules/next/dist/server/next.js
- /Users/ruslanmsv/Developer/Nextjs/approuter-2/node_modules/.pnpm/next@13.4.3-canary.0_react-dom@18.2.0_react@18.2.0/node_modules/next/dist/server/lib/render-server.js
- /Users/ruslanmsv/Developer/Nextjs/approuter-2/node_modules/.pnpm/next@13.4.3-canary.0_react-dom@18.2.0_react@18.2.0/node_modules/next/dist/compiled/jest-worker/processChild.js
    at Module._resolveFilename (node:internal/modules/cjs/loader:1082:15)
    at /Users/ruslanmsv/Developer/Nextjs/approuter-2/node_modules/.pnpm/next@13.4.3-canary.0_react-dom@18.2.0_react@18.2.0/node_modules/next/dist/server/require-hook.js:180:36
    at Module._load (node:internal/modules/cjs/loader:928:27)
    at Module.require (node:internal/modules/cjs/loader:1149:19)
    at require (node:internal/modules/helpers:121:18)
    at NextNodeServer.getPrerenderManifest (/Users/ruslanmsv/Developer/Nextjs/approuter-2/node_modules/.pnpm/next@13.4.3-canary.0_react-dom@18.2.0_react@18.2.0/node_modules/next/dist/server/next-server.js:1928:26)
    at new Server (/Users/ruslanmsv/Developer/Nextjs/approuter-2/node_modules/.pnpm/next@13.4.3-canary.0_react-dom@18.2.0_react@18.2.0/node_modules/next/dist/server/base-server.js:164:32)
    at new NextNodeServer (/Users/ruslanmsv/Developer/Nextjs/approuter-2/node_modules/.pnpm/next@13.4.3-canary.0_react-dom@18.2.0_react@18.2.0/node_modules/next/dist/server/next-server.js:172:9)
    at NextServer.createServer (/Users/ruslanmsv/Developer/Nextjs/approuter-2/node_modules/.pnpm/next@13.4.3-canary.0_react-dom@18.2.0_react@18.2.0/node_modules/next/dist/server/next.js:171:24)
    at async /Users/ruslanmsv/Developer/Nextjs/approuter-2/node_modules/.pnpm/next@13.4.3-canary.0_react-dom@18.2.0_react@18.2.0/node_modules/next/dist/server/next.js:196:31 {
  type: 'Error',
  code: 'MODULE_NOT_FOUND',
  requireStack: [
    '/Users/ruslanmsv/Developer/Nextjs/approuter-2/node_modules/.pnpm/next@13.4.3-canary.0_react-dom@18.2.0_react@18.2.0/node_modules/next/dist/server/next-server.js',
    '/Users/ruslanmsv/Developer/Nextjs/approuter-2/node_modules/.pnpm/next@13.4.3-canary.0_react-dom@18.2.0_react@18.2.0/node_modules/next/dist/server/next.js',
    '/Users/ruslanmsv/Developer/Nextjs/approuter-2/node_modules/.pnpm/next@13.4.3-canary.0_react-dom@18.2.0_react@18.2.0/node_modules/next/dist/server/lib/render-server.js',
    '/Users/ruslanmsv/Developer/Nextjs/approuter-2/node_modules/.pnpm/next@13.4.3-canary.0_react-dom@18.2.0_react@18.2.0/node_modules/next/dist/compiled/jest-worker/processChild.js'
  ]
}
 ELIFECYCLE  Command failed with exit code 1.

It seems that a problem is specific for default fetch and next: {revalidate: <number>} option. There is no problem with cache: 'no-store'

minimal example to reproduce

@Ruslanmsv
Copy link

adding
export const runtime = edge

fixes the problem 🤯🥲

@AlekseyMalakhov
Copy link
Author

I added export const runtime = "edge"; to my page.tsx
It helped to remove error during building process but when I reload the page I still get error

}
 [TypeError: fetch failed] {
  cause:  [Error: connect ECONNREFUSED ::1:3000] {
  errno: -4078,
  code: 'ECONNREFUSED',
  syscall: 'connect',
  address: '::1',
  port: 3000
}

@Ruslanmsv
Copy link

Ruslanmsv commented May 16, 2023

@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

@AlekseyMalakhov
Copy link
Author

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

@em1l1000
Copy link

I have this problem as well. It works locally but not in production. What's the best way to go around this?

@kaloyanBozhkov
Copy link

I've documented this as well, and reported a simple solution for the time being. Change the serverless function config, specifically where it's running from. A server from a different city should do the trick.

#48744

@ManuelJustMobileSec
Copy link

I'm using 13.4.4 and is still happening

@Cha-Shao
Copy link

Cha-Shao commented Jun 6, 2023

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 = 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))

@Cha-Shao
Copy link

Cha-Shao commented Jun 6, 2023

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' } ```

@kaloyanBozhkov
Copy link

I solved the issue on my side by using a fetch ponyfill. I used it for tRPC and also anywhere else I was calling fetch on the BE. Worked like a charm. It's temporary fix though.

@sehyunc
Copy link

sehyunc commented Jun 8, 2023

@kaloyanBozhkov Could you share how you implemented this temporary fix? Thanks!

@kaloyanBozhkov
Copy link

@kaloyanBozhkov Could you share how you implemented this temporary fix? Thanks!

Sure.

Here's the tRPC fix:

export const trpcClient = createTRPCProxyClient<AppRouter>({
  transformer: SuperJSON,
  links: [
    devtoolsLink({
      enabled: process.env.NODE_ENV === 'development',
    }),
    splitLink({
      condition(op) {
        // check for context property `skipBatch`
        return op.context.skipBatch === true
      },
      // when condition is true, use normal request
      true: httpLink({
        // vercel issue with fetch undici
        fetch: fetchPonyfill().fetch,
        url: `${getBaseUrl()}/api/trpc`,
      }),
      // when condition is false, use batching
      false: httpBatchLink({
        fetch: fetchPonyfill().fetch,
        url: `${getBaseUrl()}/api/trpc`,
      }),
    }),
    loggerLink({
      enabled: (opts) => opts.direction === 'down' && opts.result instanceof Error,
    }),
  ],
})

Essentially I'm ensuring that any fetch calls are using import fetchPonyfill from 'fetch-ponyfill' instead of the pre-compiled version of Undici that Vercel are using which is causing issues right now.

For the BE I implemented the ponyfill inside my existing fetch GET/POST helper, which came in handy in this specific context. Here's an example of this as well:

export async function fetchPostJSON<T>(
  url: string,
  data?: {},
  // edge functions do not have XMLHttpRequest
  usePonyfill = true
): Promise<T | Error> {
  try {
    // Default options are marked with *
    const response = await (usePonyfill ? fetchPonyfill() : { fetch }).fetch(url, {
      method: 'POST', // *GET, POST, PUT, DELETE, etc.
      ...

@kirilkirkov
Copy link

kirilkirkov commented Jun 22, 2023

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)`

@hyprnestofficial
Copy link

hyprnestofficial commented Jul 15, 2023

[17:16:29.409] Running build in Cleveland, USA (East) – cle1 [17:16:29.476] Cloning github.com/hyprnest/hyprnest (Branch: dev, Commit: aad047b) [17:16:30.065] Cloning completed: 589.124ms [17:16:33.018] Restored build cache [17:16:33.049] Running "vercel build" [17:16:33.574] Vercel CLI 31.0.3 [17:16:33.871] Installing dependencies... [17:16:41.079] [17:16:41.079] added 67 packages, removed 32 packages, and changed 32 packages in 7s [17:16:41.080] [17:16:41.080] 112 packages are looking for funding [17:16:41.080] run npm fundfor details [17:16:41.097] Detected Next.js version: 13.4.10 [17:16:41.099] Detectedpackage-lock.jsongenerated by npm 7+... [17:16:41.100] Running "npm run build" [17:16:41.404] [17:16:41.404] > hyprnest@0.1.0 build [17:16:41.405] > prisma generate && next build [17:16:41.405] [17:16:41.819] Prisma schema loaded from prisma/schema.prisma [17:16:42.237] [17:16:42.237] ✔ Generated Prisma Client (4.16.2 | library) to ./node_modules/@prisma/client in 174ms [17:16:42.237] You can now start using Prisma Client in your code. Reference: https://pris.ly/d/client [17:16:42.238] ``` [17:16:42.238] import { PrismaClient } from '@prisma/client' [17:16:42.238] const prisma = new PrismaClient() [17:16:42.238] ``` [17:16:42.827] - info Creating an optimized production build... [17:16:57.302] - info Compiled successfully [17:16:57.303] - info Linting and checking validity of types... [17:16:59.027] Pages directory cannot be found at /vercel/path0/pages or /vercel/path0/src/pages. If using a custom path, please configure with theno-html-link-for-pages rule in your eslint config file. [17:17:01.724] - info Collecting page data... [17:17:18.903] - info Generating static pages (0/10) [17:17:18.985] - info Generating static pages (2/10) [17:17:19.078] - info Generating static pages (4/10) [17:17:19.167] - info Generating static pages (7/10) [17:17:19.327] Error: Failed to fetch data [17:17:19.327] at getData (/vercel/path0/.next/server/app/dashboard/page.js:754:15) [17:17:19.327] at process.processTicksAndRejections (node:internal/process/task_queues:95:5) [17:17:19.327] at async dashboard (/vercel/path0/.next/server/app/dashboard/page.js:759:18) [17:17:19.345] [17:17:19.345] Error occurred prerendering page "/dashboard". Read more: https://nextjs.org/docs/messages/prerender-error [17:17:19.345] Error: Failed to fetch data [17:17:19.345] at getData (/vercel/path0/.next/server/app/dashboard/page.js:754:15) [17:17:19.345] at process.processTicksAndRejections (node:internal/process/task_queues:95:5) [17:17:19.345] at async dashboard (/vercel/path0/.next/server/app/dashboard/page.js:759:18) [17:17:19.345] [17:17:19.345] > Export encountered errors on following paths: [17:17:19.346] /dashboard/page: /dashboard [17:17:19.346] - info Generating static pages (10/10) [17:17:19.407] Error: Command "npm run build" exited with 1

inside app/dashboard/page.tsx i am using a async function to fetch from an api. The build keeps failing on vercel but locally it works

@decorsstudio
Copy link

decorsstudio commented Jul 18, 2023

Nextjs team, it is still a big blocker, the same I am facing. locally it works fine but production build getting same error
image
even error.tsx not catching. showing blank page instead. Please help, give us any solution as we are trying to upgrade our project from 12 to 13 using app directory. plz plz

@timneutkens
Copy link
Member

timneutkens commented Jul 18, 2023

Unfortunately there is almost no code shared in this issue which makes it quite hard to provide a definitive answer. But looking at the error messages it seems that a bunch of the reports are related to trying to fetch api routes / route handlers in server components / getServerSideProps / getStaticProps. You can't fetch api routes / route handlers in that way because during next build there is no server running. You can run the code in the api route directly in server components, no indirection going to the route handler needed for that case, same as trying to fetch api routes in pages.

@mononoke-choi
Copy link

Unfortunately there is almost no code shared in this issue which makes it quite hard to provide a definitive answer. But looking at the error messages it seems that a bunch of the reports are related to trying to fetch api routes / route handlers in server components / getServerSideProps / getStaticProps. You can't fetch api routes / route handlers in that way because during next build there is no server running. You can run the code in the api route directly in server components, no indirection going to the route handler needed for that case, same as trying to fetch api routes in pages.

i'm curious,
how could i run build command this repository on local machine successfully?
it uses getBaseUrl function to access route handler on local at 'localhost:3000'.
i just followed vercel's example and i faced same issue too

@abranaf
Copy link

abranaf commented Jul 20, 2023

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 :(

@bobkataboo
Copy link

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

@Cha-Shao
Copy link

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

My suggestion is that the SSR component directly reads and writes the database in tsx, and the client component then uses fetch

@nomandhoni-cs
Copy link

@abranaf I am facing the same issue! Have you found any solution?

@zaunermax
Copy link

@timneutkens I can share the code to my portfolio website (which is not done yet) but I also run into this issue. The build is failing on the main page. To give a little bit more context: The <Suggestions> component is a RSC which fetches some suggestions from a next api handler. The curious part is, that I use the <Suggestions/> component elsewhere, but that page is rendered as "Server" not as "Static" (according to build logs) so the problem does not occur.

Route (app)                                Size     First Load JS
┌ ○ /                                      150 B          81.4 kB
├ ○ /api/suggestions                       0 B                0 B
├ ○ /favicon.ico                           0 B                0 B
├ ○ /main                                  22.4 kB         117 kB
├ ○ /main/education                        150 B          81.4 kB
├ ○ /main/projects                         150 B          81.4 kB
├ λ /main/query                            5.96 kB         101 kB
├ ○ /main/work                             148 B          81.4 kB
└ λ /studio/[[...index]]                   693 kB          777 kB
+ First Load JS shared by all              81.3 kB
  ├ chunks/833-b9fcb5c494e8748b.js         26.4 kB
  ├ chunks/f582f327-0d606f8131060edf.js    52.7 kB
  ├ chunks/main-app-68cb0c0d71576819.js    221 B
  └ chunks/webpack-3842ea67ab37a518.js     1.96 kB

Route (pages)                              Size     First Load JS
─ ○ /404                                   182 B          76.1 kB
+ First Load JS shared by all              75.9 kB
  ├ chunks/framework-f780fd9bae3b8c58.js   45.1 kB
  ├ chunks/main-c2544a9110662c07.js        28.7 kB
  ├ chunks/pages/_app-ed9f7378ac74196d.js  198 B
  └ chunks/webpack-3842ea67ab37a518.js     1.96 kB

so my main page uses the <Suggestions/> and there it fails to fetch (now it does not because I have a fallback .catch() but the fetch fails during the prod build - I've just console logged the error to make it visible:

[    ] - info Generating static pages (0/9)TypeError: fetch failed
    at Object.fetch (node:internal/deps/undici/undici:11413: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: -4078,
    code: 'ECONNREFUSED',
    syscall: 'connect',
    address: '127.0.0.1',
    port: 3000
  }
}

my main/query page also uses the <Suggestions/> RSC in the same way, with <Suspense> and so on but that one works. You can see that because the route handler has some console log which says "did a thing..." which is displayed in the build output.

[=== ] - info Generating static pages (8/9)did a thing...

Could it be that the api routes are not active while building the static pages? That it might be an order of execution thing? 🤔

Also some observations I've made:

  • Building locally fails every time. The only way I can make it work is to pnpm next build - then pnpm next start and then in parallel do pnpm next build again...
  • On vercel it works now, because once you've built once and the deplyoment is running it can just fetch the currently deployed URL to build the static pages.

Here is the link to the main page of my portfolio which causes the build to fail.

@zaunermax
Copy link

Another observation I've made: setting dynamic to force-dynamic in main seems to solve the issue as well.

@MrZhouZh
Copy link

MrZhouZh commented Aug 3, 2023

Same error! on next@13.4.12 and deployment in vercel

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: -61,
    code: 'ECONNREFUSED',
    syscall: 'connect',
    address: '::1',
    port: 3000
  }
}

Error occurred prerendering page "/todos". Read more: https://nextjs.org/docs/messages/prerender-error

@MrZhouZh
Copy link

MrZhouZh commented Aug 3, 2023

main

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

@jthomaschewski
Copy link

jthomaschewski commented Aug 7, 2023

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)

@b1rdex
Copy link

b1rdex commented Aug 8, 2023

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.

@b1rdex
Copy link

b1rdex commented Aug 8, 2023

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.

@timneutkens
Copy link
Member

Please read my earlier reply on this issue: #49578 (comment)

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.

@b1rdex
Copy link

b1rdex commented Aug 9, 2023

@timneutkens here is a reprodution: https://github.com/b1rdex/next.js-fetch-error

@katewayo
Copy link

katewayo commented Aug 9, 2023

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. (/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. (/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
    }
    }

@zaunermax
Copy link

@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.

@timneutkens ah now I understand the point of confusion. I am using a BFF approach because the only thing that can be cached via static regeneration is next's fetch function as far as I can understand from the documentation? Maybe I am wrong though, if so I am sorry. I need the indirection, because otherwise I was not able to cache the requests to the CMS. Some of the sites are built as λ (Server) server-side renders at runtime so they're not cached at all... Maybe I am missing a better way to do this?

@stx-chris
Copy link

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)

@katewayo
Copy link

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.

@kodiakhq kodiakhq bot closed this as completed in #53131 Aug 14, 2023
kodiakhq bot pushed a commit that referenced this issue Aug 14, 2023
### What?
This PR makes it easier to use Next.js with IPv6 hostnames such as `::1` and `::`.

### How?
It does so by removing rewrites from `localhost` to `127.0.0.1` introduced in #52492. It also fixes the issue where Next.js tries to fetch something like `http://::1:3000` when `--hostname` is `::1` as it is not a valid URL (browsers' `URL` class throws an error when constructed with such hosts). It also fixes `NextURL` so that it doesn't accept `http://::1:3000` but refuse `http://[::1]:3000`. It also changes `next/src/server/lib/setup-server-worker.ts` so that it uses the server's `address` method to retrieve the host instead of our provided `opts.hostname`, ensuring that no matter what `opts.hostname` is we will always get the correct one.

### Note
I've verified that `next dev`, `next start` and `node .next/standalone/server.js` work with IPv6 hostnames (such as `::` and `::1`), IPv4 hostnames (such as `127.0.0.1`, `0.0.0.0`) and `localhost` - and with any of these hostnames fetching to `localhost` also works. Server Actions and middleware have no problems as well.

This also removes `.next/standalone/server.js`'s logging as we now use `start-server`'s logging to avoid duplicates. `start-server`'s logging has also been updated to report the actual hostname.
![image](https://github.com/vercel/next.js/assets/75556609/cefa5f23-ff09-4cef-a055-13eea7c11d89)
![image](https://github.com/vercel/next.js/assets/75556609/619e82ce-45d9-47b7-8644-f4ad083429db)
The above pictures also demonstrate using Server Actions with Next.js after this PR.
![image](https://github.com/vercel/next.js/assets/75556609/3d4166e9-f950-4390-bde9-af2547658148)

Fixes #53171
Fixes #49578
Closes NEXT-1510

Co-authored-by: Tim Neutkens <6324199+timneutkens@users.noreply.github.com>
Co-authored-by: Zack Tanner <1939140+ztanner@users.noreply.github.com>
@smaccoun
Copy link

Did #53131 fix this for everyone? It went in to release 13.4.15 and I'm on 13.4.18 and still seeing it intermittently

@eldenpark

This comment has been minimized.

@timneutkens
Copy link
Member

Feel free to open a new issue following the issue template providing a reproduction so that we can investigate.

@vercel vercel locked as off-topic and limited conversation to collaborators Aug 21, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
bug Issue was opened via the bug report template. Pages Router Related to Pages Router.
Projects
None yet
Development

Successfully merging a pull request may close this issue.