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

[NEXT-1190] TypeError: fetch failed in server componant since next 13.0.6 #44062

Closed
1 task done
sylvain-guehria opened this issue Dec 15, 2022 · 75 comments
Closed
1 task done
Labels
bug Issue was opened via the bug report template. linear: next Confirmed issue that is tracked by the Next.js team. locked

Comments

@sylvain-guehria
Copy link

sylvain-guehria commented Dec 15, 2022

Verify canary release

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

Provide environment information

Operating System:
Platform: linux
Arch: x64
Version: #62-Ubuntu SMP Tue Nov 22 19:54:14 UTC 2022
Binaries:
Node: 18.12.0
npm: 8.19.2
Yarn: 1.22.19
pnpm: N/A
Relevant packages:
next: 13.0.6
eslint-config-next: 13.0.0
react: 18.2.0
react-dom: 18.2.0

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/sylvain-guehria/StockShop

To Reproduce

I log here : https://inventory-market.vercel.app/ and that it's

Describe the Bug

when I log, a server componant fetch data. This was working this morning but after installing next 13.0.6 I got this error only in prod :

error validating user TypeError: fetch failed
at Object.fetch (/var/task/node_modules/next/dist/compiled/undici/index.js:1:26684)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async validateUser (/var/task/.next/server/app/page.js:740:21)
at async HomePage (/var/task/.next/server/app/page.js:674:17) {
cause: TypeError: Cannot read properties of undefined (reading 'reason')
at makeAppropriateNetworkError (/var/task/node_modules/next/dist/compiled/undici/index.js:2:54604)
at schemeFetch (/var/task/node_modules/next/dist/compiled/undici/index.js:2:30000)
at /var/task/node_modules/next/dist/compiled/undici/index.js:2:28607
at mainFetch (/var/task/node_modules/next/dist/compiled/undici/index.js:2:29007)
at httpRedirectFetch (/var/task/node_modules/next/dist/compiled/undici/index.js:2:33708)
at httpFetch (/var/task/node_modules/next/dist/compiled/undici/index.js:2:32580)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async schemeFetch (/var/task/node_modules/next/dist/compiled/undici/index.js:2:30793)
at async /var/task/node_modules/next/dist/compiled/undici/index.js:2:28601
at async mainFetch (/var/task/node_modules/next/dist/compiled/undici/index.js:2:28426)
}

Expected Behavior

no fetch error, either the result is null or a string.

Which browser are you using? (if relevant)

chrome

How are you deploying your application? (if relevant)

vercel

NEXT-1190

@sylvain-guehria sylvain-guehria added the bug Issue was opened via the bug report template. label Dec 15, 2022
@Pnlvfx
Copy link

Pnlvfx commented Dec 15, 2022

Same

@mapringg
Copy link

I no longer see the code that you attached. Are you fetching one of the API route with fetch within getSeverSideProps because that is not possible?

@sylvain-guehria
Copy link
Author

Sorry, I solved it by removing the fetch from the layout and put it in the page. I used the new way to fetch data in a server component.

But we should be able to fetch data in the layout. The problem came with the upgrade from Next 13.0.5 to 13.0.6

@timheerwagen
Copy link

timheerwagen commented Jan 18, 2023

I get the same error in Next.js version 13.1.2. Still using the pages directory. Whether locally or on the server, the behaviour remains the same. No external fetch requests work and not even external images can be loaded with sharp. With Next.js version 12 everything worked fine.

TypeError: fetch failed
   at Object.fetch (node:internal/deps/undici/undici:14062:11)
   at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
   at async imageOptimizer (node_modules\next\dist\server\image-optimizer.js:472:29

Has anyone found a workaround?

@Anas-Nabulsi
Copy link

I managed to solve this problem by using 127.0.0.1 instead of localhost in the fetch URL

@timheerwagen
Copy link

timheerwagen commented Feb 25, 2023

My current solution is to put the following at the beginning of next.config.js

const dns = require("dns");

dns.setDefaultResultOrder("ipv4first")

The reason is Node17/18 using ipv6 as default for localhost. node-fetch/node-fetch#1624

@professorhaseeb
Copy link

I'm getting this error on next:12.3.3 deployed on Vercel,
works fine locally though

@trazyn
Copy link

trazyn commented Mar 10, 2023

node: 18
next: 13.2.3
deployed on Vercel

TypeError: fetch failed
    at Object.fetch (node:internal/deps/undici/undici:14062:11)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)

change to nodejs 16 works fine 🙃

@arjendevos
Copy link

Still an issue:

{
  error: TypeError: fetch failed
      at Object.processResponse (node:internal/deps/undici/undici:7188:34)
      at node:internal/deps/undici/undici:7516:42
      at node:internal/process/task_queues:140:7
      at AsyncResource.runInAsyncScope (node:async_hooks:202:9)
      at AsyncResource.runMicrotask (node:internal/process/task_queues:137:8)
      at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
    cause: Error: [object Object]
        at makeNetworkError (node:internal/deps/undici/undici:6317:51)
        at httpNetworkFetch (node:internal/deps/undici/undici:7810:16)
        at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
        at async httpNetworkOrCacheFetch (node:internal/deps/undici/undici:7703:33)
        at async httpFetch (node:internal/deps/undici/undici:7557:37)
        at async schemeFetch (node:internal/deps/undici/undici:7489:18)
        at async node:internal/deps/undici/undici:7342:20
        at async mainFetch (node:internal/deps/undici/undici:7338:20) {
      [cause]: undefined
    }
  }
}```

node: 18.0.0 and tested with node 16.19.1

```json
"@types/node": "18.15.3",
    "@types/react": "18.0.28",
    "@types/react-dom": "18.0.11",
    "eslint": "8.36.0",
    "eslint-config-next": "13.2.4",
    "next": "^13.2.4",
    "react": "18.2.0",
    "react-dom": "18.2.0",
    "sass": "^1.59.3",
    "typescript": "4.9.5"

@Puharesource
Copy link

For me this issue was caused by using self signed certificates for my development backend server.
I simply added NODE_TLS_REJECT_UNAUTHORIZED=0 to my .env.local file located in the root of the project.

@hk86
Copy link

hk86 commented Apr 3, 2023

Not an issue for me with version 13.2.4, but using the latest canary of 13.2.5 broke it on local Windows machine using dev.

error - TypeError: fetch failed
    at Object.fetch (node:internal/deps/undici/undici:11118:11)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async Object.fn (C:\Projects\nextapp\sites\node_modules\next\dist\server\next-server.js:917:43)
    at async Router.execute (C:\Projects\nextapp\sites\node_modules\next\dist\server\router.js:293:32)
    ... 2 lines matching cause stack trace ...
    at async DevServer.handleRequestImpl (C:\Projects\nextapp\sites\node_modules\next\dist\server\base-server.js:437:20) {
  cause: InvalidArgumentError: invalid connection header
      at processHeader (node:internal/deps/undici/undici:6504:15)
      at new Request (node:internal/deps/undici/undici:6387:13)
      at [dispatch] (node:internal/deps/undici/undici:7359:25)
      at Intercept (node:internal/deps/undici/undici:7119:20)
      at [Intercepted Dispatch] (node:internal/deps/undici/undici:413:16)
      at Client.dispatch (node:internal/deps/undici/undici:429:44)
      at [dispatch] (node:internal/deps/undici/undici:648:32)
      at [Intercepted Dispatch] (node:internal/deps/undici/undici:406:33)
      at Pool.dispatch (node:internal/deps/undici/undici:429:44)
      at [dispatch] (node:internal/deps/undici/undici:8649:27)
      at Intercept (node:internal/deps/undici/undici:7119:20)
      at [Intercepted Dispatch] (node:internal/deps/undici/undici:413:16)
      at Agent.dispatch (node:internal/deps/undici/undici:429:44)
      at node:internal/deps/undici/undici:11010:83
      at new Promise (<anonymous>)
      at dispatch (node:internal/deps/undici/undici:11010:16)
      at httpNetworkFetch (node:internal/deps/undici/undici:10917:65)
      at httpNetworkOrCacheFetch (node:internal/deps/undici/undici:10819:39)
      at httpFetch (node:internal/deps/undici/undici:10671:43)
      at schemeFetch (node:internal/deps/undici/undici:10607:24)
      at node:internal/deps/undici/undici:10483:26
      at mainFetch (node:internal/deps/undici/undici:10500:11)
      at fetching (node:internal/deps/undici/undici:10457:7)
      at Agent.fetch2 (node:internal/deps/undici/undici:10337:20)
      at Object.fetch (node:internal/deps/undici/undici:11116:28)
      at fetch (node:internal/process/pre_execution:216:25)
      at Object.fn (C:\Projects\nextapp\sites\node_modules\next\dist\server\next-server.js:917:49)
      at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
      at async Router.execute (C:\Projects\nextapp\sites\node_modules\next\dist\server\router.js:293:32)
      at async DevServer.runImpl (C:\Projects\nextapp\sites\node_modules\next\dist\server\base-server.js:494:29)
      at async DevServer.run (C:\Projects\nextapp\sites\node_modules\next\dist\server\dev\next-dev-server.js:860:20)
      at async DevServer.handleRequestImpl (C:\Projects\nextapp\sites\node_modules\next\dist\server\base-server.js:437:20) {
    code: 'UND_ERR_INVALID_ARG'
  }
}

@shriekdj
Copy link

shriekdj commented Apr 5, 2023

thanks buddy my issue solved

@devhady
Copy link

devhady commented Apr 9, 2023

thanks buddy my issue solved

can u tell us how please ?

@shriekdj
Copy link

shriekdj commented Apr 9, 2023

thanks buddy my issue solved

can u tell us how please ?

actually i had my backend api on localhost and this fetch was not working on http://localhost:8000 but, after some time it is working on at http://127.0.0.1:8000.

So that time I found out this, that nextjs 13 fetch does not work for localhost api

@xhxe
Copy link

xhxe commented Apr 16, 2023

Error appears most likely on node 18, I downgraded version to 16 and issue got fixed

@miyahironari
Copy link

I got the same errors and solved it.

e.g.

  const fetchUserInfo = async () => {
    const data = await fetch(
      process.env.API_URL + "/api/userIdByUsername/" + username
    )

    const json = await data.json()
    return json.user
  }

.env

API_URL=http://localhost:3000

run npm run build and npm run start

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 ::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: 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: '3855851030'
}

then I tried modify .env following:

API_URL=http://127.0.0.1:3000

it works fine.

@jabedzaman
Copy link

My solution to this was keep your dev server running while deploying it on vercel or ceating a local build... 💀

@kevlarr
Copy link

kevlarr commented May 1, 2023

I managed to solve this problem by using 127.0.0.1 instead of localhost in the fetch URL

@Anas-Nabulsi You are my hero, this resolved fetch issues in getting server-side props, as it did for others. Thanks for pointing it out.

@sapomaro
Copy link

sapomaro commented May 3, 2023

I have similar error (ERR_INVALID_URL) with server-side fetch. Changing to 127.0.0.1 and other above-mentioned solutions don't work (haven't tried downgrading though). Calling external resources is blocked as well.

error - TypeError: Failed to parse URL from httр://localhost:3000/api/test
    at Object.fetch (node:internal/deps/undici/undici:14152:11)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async handler (webpack-internal:///(api)/./src/pages/api/checkout.js:8:20)
    at async Object.apiResolver (XXX\node_modules\next\dist\server\api-utils\node.js:372:9)
    at async DevServer.runApi (XXX\node_modules\next\dist\server\next-server.js:514:9)
    ... 5 lines matching cause stack trace ...
    at async XXX\node_modules\next\dist\server\base-server.js:157:99 {
  page: '/api/checkout',
  [cause]: TypeError [ERR_INVALID_URL]: Invalid URL
      at new NodeError (node:internal/errors:399:5)
      at URL.onParseError (node:internal/url:565:9)
      at new URL (node:internal/url:645:5)
      at new Request (node:internal/deps/undici/undici:6947:25)
      at fetch2 (node:internal/deps/undici/undici:13315:25)
      at Object.fetch (node:internal/deps/undici/undici:14150:18)
      at fetch (node:internal/process/pre_execution:241:25)
      at infoAPI (webpack-internal:///(api)/./src/modules/reporting/api/infoAPI.js:17:12)
      at handler (webpack-internal:///(api)/./src/pages/api/checkout.js:8:100)
      at Object.apiResolver (XXX\node_modules\next\dist\server\api-utils\node.js:372:15)
      at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
      at async DevServer.runApi (XXX\node_modules\next\dist\server\next-server.js:514:9)
      at async Object.fn (XXX\node_modules\next\dist\server\next-server.js:828:35)
      at async Router.execute (XXX\node_modules\next\dist\server\router.js:243:32)
      at async DevServer.runImpl (XXX\node_modules\next\dist\server\base-server.js:432:29)
      at async DevServer.run (XXX\node_modules\next\dist\server\dev\next-dev-server.js:831:20)
      at async DevServer.handleRequestImpl (XXX\node_modules\next\dist\server\base-server.js:375:20)
      at async XXX\node_modules\next\dist\server\base-server.js:157:99 {
    input: 'httр://localhost:3000/api/test',
    code: 'ERR_INVALID_URL'
  }
}

I'm running Next v13.2.4 (dev mode) on Node v19.4.0 (Windows 10).

More info: https://stackoverflow.com/questions/76148113/nextjs-server-side-fetch-typeerror-failed-to-parse-url-from-htt%d1%80-localhost

@sapomaro
Copy link

sapomaro commented May 3, 2023

I have similar error (ERR_INVALID_URL) with server-side fetch. Changing to 127.0.0.1 and other above-mentioned solutions don't work (haven't tried downgrading though). Calling external resources is blocked as well.

It turned out that the URL was actually illegal. Sometimes invisible Unicode characters (like zero width non-joiner U+200C) can appear in unexpected places and it's kinda hard to hunt them down: https://invisible-characters.com/

@yano3nora
Copy link

yano3nora commented May 7, 2023

I'm encountering the same error in a Docker environment.

  • Versions: node@16.20.0, next@13.3.4, next-auth@4.22.1
  • Environment: macOS, running next dev in Docker (local development)
  • Bug:
    1. Calling getSession() within getServerSideProps in pages/index.tsx
    2. fetch to http://localhost:3000/api/auth/session from getSession() fails

I'm writing this for others as I couldn't find a similar workaround.

# .env
# https://next-auth.js.org/configuration/options#nextauth_url_internal
NEXTAUTH_URL_INTERNAL=http://127.0.0.1:3000
import { getServerSession } from 'next-auth'
import { authOptions } from 'pages/api/auth/[...nextauth]'

export const getServerSideProps = async (context) => {
  /**
   * using getServerSession instead of getSession (also api route)
   * @ref https://next-auth.js.org/configuration/nextjs#getserversession
   */
  const session = await getServerSession(context.req, context.res, authOptions)
  // ...
}
Error body
nextjs-1        | [next-auth][error][CLIENT_FETCH_ERROR] 
nextjs-1        | https://next-auth.js.org/errors#client_fetch_error fetch failed {
nextjs-1        |   error: {
nextjs-1        |     message: 'fetch failed',
nextjs-1        |     stack: 'TypeError: fetch failed\n' +
nextjs-1        |       '    at Object.fetch (/app/node_modules/next/dist/compiled/undici/index.js:1:26669)\n' +
nextjs-1        |       '    at processTicksAndRejections (node:internal/process/task_queues:96:5)',
nextjs-1        |     name: 'TypeError'
nextjs-1        |   },
nextjs-1        |   url: 'http://localhost:3000/api/auth/session',
nextjs-1        |   message: 'fetch failed'
nextjs-1        | }

@ijjk
Copy link
Member

ijjk commented May 11, 2023

Hi, since the original reproduction is no longer available, could someone who was experiencing this issue please confirm it is still an issue in the latest version of Next.js v13.4.1?

@cyrine25
Copy link

yes i still have this issue :
`TypeError: fetch failed
at Object.fetch (/home/runner/work/next-ts-app/next-ts-app/node_modules/next/dist/compiled/undici/index.js:1:26669)
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
cause: Error: connect ECONNREFUSED 127.0.0.1:3000
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1278: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 "/questions". Read more: https://nextjs.org/docs/messages/prerender-error
TypeError: fetch failed

  • info Generating static pages (6/6)
    at Object.fetch (/home/runner/work/next-ts-app/next-ts-app/node_modules/next/dist/compiled/undici/index.js:1:26669)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)

Export encountered errors on following paths:
/questions/page: /questions
Error: Process completed with exit code 1.`

the fetch url i use when my local server is running :
http://127.0.0.1:3000/data/questions.json
next version : 13.4.1

@timneutkens
Copy link
Member

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

@arnasofc
Copy link

what do you mean? Can you give an example and how to fix?

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

@arnasofc
Copy link

I fixed the issue by using http://127.0.0.1:3000 and adding to every fetch request (cache: 'no-store',)

@kirilkirkov
Copy link

@jabedzaman
@KoolP

I think that the best solution will be with - fallback data.. and immediately after build to remove the .next/cache/fetch-cache/* contents.
In this way.. can use the fetch function with bigger revalidation time or full cache (which is by default).
I think that currently this is the only way to use fetch with cache, to use build in docker and everything to works in normal behavior.

@jaredonline
Copy link

jaredonline commented Jun 25, 2023

@kirilkirkov check out this thread on the Fly.io forums where I've gotten some help figuring this out: https://community.fly.io/t/nextjs-build-vs-runtime-environment-variables/13760/9?u=jared1

@sanalpanicker

"but my understanding is that the fetch shouldn't be attempted in the build context at all".
This is a react server component and it will be prerendered during the build time.
Read more here : https://nextjs.org/learn/foundations/how-nextjs-works/buildtime-and-runtime

The folks at Fly.io helped me figure out what's going on here; the difference between dynamic and static rendering of server-side components. The NextJS docs on the topic say that using cache: 'no-store' should switch the component to dynamic rendering. It doesn't appear to be working as intended (should I open a bug?). But if I use the cookies() method, it does switch to dynamic rendering and skip this component entirely in the pre-render phase of next build.

Either the docs are wrong, or there's a bug somewhere. cc @timneutkens

@Kurre
Copy link

Kurre commented Jun 26, 2023

@kirilkirkov check out this thread on the Fly.io forums where I've gotten some help figuring this out: https://community.fly.io/t/nextjs-build-vs-runtime-environment-variables/13760/9?u=jared1

@sanalpanicker

"but my understanding is that the fetch shouldn't be attempted in the build context at all".
This is a react server component and it will be prerendered during the build time.
Read more here : https://nextjs.org/learn/foundations/how-nextjs-works/buildtime-and-runtime

The folks at Fly.io helped me figure out what's going on here; the difference between dynamic and static rendering of server-side components. The NextJS docs on the topic say that using cache: 'no-store' should switch the component to dynamic rendering. It doesn't appear to be working as intended (should I open a bug?). But if I use the cookies() method, it does switch to dynamic rendering and skip this component entirely in the pre-render phase of next build.

Either the docs are wrong, or there's a bug somewhere. cc @timneutkens

If the dynamic mode isn't automatically detected, you can also use https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config#dynamic to force it.

@yiGmMk
Copy link

yiGmMk commented Jun 27, 2023

got the same issue when fetch 'https://api.github.com/users/yiGmMk',in my case it's caused by api limit
the same code works with another api 'https://jsonplaceholder.typicode.com/posts/1'
export async function getServerSideProps() { const res = await fetch('https://jsonplaceholder.typicode.com/posts/1'); if (!res.ok) { throw new Error("fetch user failed") } const user = await res.json(); return { props: { data: user } }; }

@LeandroVCastro
Copy link

If the dynamic mode isn't automatically detected, you can also use https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config#dynamic to force it is necessary.

This was what I did and this works for me like a charm.

@Eliav2
Copy link

Eliav2 commented Jul 2, 2023

If the dynamic mode isn't automatically detected, you can also use https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config#dynamic to force it.res.json(); return { props: { data: user } }; }`

Thank you!
adding in page.tsx:

export const dynamic = 'force-dynamic'

worked like charm. I wished nextjs could automatically detect the right behavior... doesn't feel like app directory is production ready for me

@LeandroVCastro
Copy link

Is there some PR or issue to investigate and fix this behavior?

@bripkens
Copy link

fyi in case you are facing issues due to process.env. usage: There is a workaround within #50828 (comment) showing how to opt into dynamic rendering using headers.

@taracila
Copy link

Recently, I've updated my local setup and got the same issue.
My local settings:

node -v
v18.16.1

yarn -v
3.6.1

npm -v
9.5.1

next -v
13.4.9

To fix TypeError: fetch failed, just add to your package.json scripts --dns-result-order=ipv4first:

"scripts": {
    "dev": "NODE_OPTIONS='--dns-result-order=ipv4first' next dev",
}

@x86developers
Copy link

My current solution is to put the following at the beginning of next.config.js

const dns = require("dns");

dns.setDefaultResultOrder("ipv4first")

The reason is Node17/18 using ipv6 as default for localhost. node-fetch/node-fetch#1624

This worked for my problem

@Ashkumar7
Copy link

was facing same issue in serverside component , to fix it changed my url to http://[::1]:8000 from http://127.0.0.1:8000

@Focus-me34
Copy link

I looked for this issue for quite a while with a Rails 7 backend and came to these conclusions:

  • This is the next server sending the request and not the client (obviously).
  • When sending fetch requests from the client (using createAsyncThunk or action creators from Redux, or useEffect hook) the Origin header is always present.
  • When sending requests from a server component, the Origin header is usually missing. Calling request.origin in the body of the controller's action was returning nil.

Knowing that, I started to manually specify the Origin header in my fetch requests and this solved my issue.
Maybe you guys are having a somewhat different problem, but I thought it might be great to share my solution to this problem with you.

Worth mentioning as well, I'm using a .env variable to define the Origin in my fetch requests and then using process.env.NEXT_PUBLIC_ORIGIN to access the value like so:

    const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/v1/xxx`, {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${token}`,
        Origin: `${process.env.NEXT_PUBLIC_ORIGIN}`,
      },
      next: {
        revalidate: 5,
      },
    });

Don't forget to add your .env variables in the var settings section of your website on your hosting platform (eg. Heroku).

@amirwsin
Copy link

amirwsin commented Jul 15, 2023

so in my In my scenario, I am using Django as the backend for my Next.js app. I make a request to /api/inventory/products in Next.js, which in it call fetch to Django's REST framework.

To work around the "fetch failed" during build time, I followed these steps:

  1. I copied my Next.js app to another directory, so can run it seperatly from original as otherwise couldnt run build command.
  2. I ran the copied Next.js app in development mode with Django running.
  3. Then, in the original directory, I initiated the build process.
  4. During the build, Next.js called the development mode server, which handled the fetches and completed the build.

Please note that this is only a temporary workaround, but it has been effective for me.
2023-07-15_19-05-36

@jeffmlb91
Copy link

I am running into the same issue doing a fetch call
I have a getFetchUrl.ts which holds the following:

export const getFetchUrl = (route: string) =>
  `${
    process.env.NODE_ENV === "production"
      ? process.env.VERCEL_URL!
      : "http://127.0.0.1:3001"
  }/${route}`;

and my page.tsx

import { getFetchUrl } from "@/lib/getFetchUrl";
import { PageResult, SearchParams } from "@/typing";
import { redirect } from "next/navigation";

type Props = {
  searchParams: SearchParams;
  params: {
    term: string;
  };
};

async function SearchPage({ searchParams, params: { term } }: Props) {
  if (!term) {
    redirect("/");
  }

  {
    /**Fetch from API... */
  }
  const response = await fetch(getFetchUrl("api/search"), {
    method: "POST",
    body: JSON.stringify({ searchTerm: term, ...searchParams }),
  });

  const results = await (response.json()) as PageResult[];
  console.log(results);

  return <div>{/**Result list */}</div>;
}

export default SearchPage;

@JacobGrady
Copy link

JacobGrady commented Jul 19, 2023

I was able to fix this by wrapping the fetch in a try/catch, like so:

try {
  const res = await fetch(_____, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' }
  });

  if (!res.ok) {
    throw new Error('Failed to fetch data');
  }

  return res.json();
} catch (e) {
  return {};
}

@jeffmlb91
Copy link

jeffmlb91 commented Jul 20, 2023

I tried the below and getting status OK on the network but no data is being returned

async function SearchPage({ searchParams, params: { term } }: Props) {
  if (!term) {
    redirect("/");
  }

  try {
    const response = await fetch(getFetchUrl("api/search"), {
      method: "POST",
      body: JSON.stringify({ searchTerm: term, ...searchParams }),
    });

    if (!response.ok) {
      // Handle non-successful responses (e.g., 404, 500, etc.)
      throw new Error("API Error: " + response.status);
    }

    const results = await response.json();
    console.log(results);

    return <div>{/** Result list */}</div>;
  } catch (error) {
    // Handle fetch-related errors
    console.error("Fetch Error:", error);
   
    return <div>Error fetching data. Please try again later.</div>;
  }
}

@abranaf
Copy link

abranaf commented Jul 20, 2023

I was able to fix this by wrapping the fetch in a try/catch, like so:

try {
  const res = await fetch(_____, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' }
  });

  if (!res.ok) {
    throw new Error('Failed to fetch data');
  }

  return res.json();
} catch (e) {
  return {};
}

well yeah, I tried the same thing, doesn't break but no data is returned so nothing is rendered in the Page where I'm using that data

@Sumitmaithani
Copy link

Sumitmaithani commented Jul 23, 2023

I also getting this error on next@13.4.12 everything works fine on locally but getting this error on deployment in vercel.

changed localhost:3000 to 127.0.0.1:3000 not worked

Want to see my code details https://github.com/Sumitmaithani/competency-passbook

Error loading courses:  TypeError: fetch failed
--
20:25:18.646 | at Object.fetch (node:internal/deps/undici/undici:11457:11)
20:25:18.646 | at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
20:25:18.647 | cause: Error: connect ECONNREFUSED 127.0.0.1:3000
20:25:18.647 | at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1494:16)
20:25:18.647 | at TCPConnectWrap.callbackTrampoline (node:internal/async_hooks:130:17) {
20:25:18.648 | errno: -111,
20:25:18.649 | code: 'ECONNREFUSED',
20:25:18.649 | syscall: 'connect',
20:25:18.657 | address: '127.0.0.1',
20:25:18.657 | port: 3000
20:25:18.657 | }

@Ashkumar7
Copy link

I also getting this error on next@13.4.12 everything works fine on locally but getting this error on deployment in vercel.

changed localhost:3000 to 127.0.0.1:3000 not worked

Want to see my code details https://github.com/Sumitmaithani/competency-passbook

Error loading courses:  TypeError: fetch failed
--
20:25:18.646 | at Object.fetch (node:internal/deps/undici/undici:11457:11)
20:25:18.646 | at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
20:25:18.647 | cause: Error: connect ECONNREFUSED 127.0.0.1:3000
20:25:18.647 | at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1494:16)
20:25:18.647 | at TCPConnectWrap.callbackTrampoline (node:internal/async_hooks:130:17) {
20:25:18.648 | errno: -111,
20:25:18.649 | code: 'ECONNREFUSED',
20:25:18.649 | syscall: 'connect',
20:25:18.657 | address: '127.0.0.1',
20:25:18.657 | port: 3000
20:25:18.657 | }

Wait what?? Why would u use localhost in production after deploying??

@sorakhan
Copy link

I also getting this error on next@13.4.12 everything works fine on locally but getting this error on deployment in vercel.

changed localhost:3000 to 127.0.0.1:3000 not worked

Want to see my code details https://github.com/Sumitmaithani/competency-passbook

Error loading courses:  TypeError: fetch failed
--
20:25:18.646 | at Object.fetch (node:internal/deps/undici/undici:11457:11)
20:25:18.646 | at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
20:25:18.647 | cause: Error: connect ECONNREFUSED 127.0.0.1:3000
20:25:18.647 | at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1494:16)
20:25:18.647 | at TCPConnectWrap.callbackTrampoline (node:internal/async_hooks:130:17) {
20:25:18.648 | errno: -111,
20:25:18.649 | code: 'ECONNREFUSED',
20:25:18.649 | syscall: 'connect',
20:25:18.657 | address: '127.0.0.1',
20:25:18.657 | port: 3000
20:25:18.657 | }

I kept getting the above in Vercel logs and would also see the following error in my app:

image

These are the steps that worked for me:

  1. I needed to create a .env.production.local with NEXT_PUBLIC_BASE_URL=<app_domain>
  2. Then ran the usual Vercel commands for building and deploying:
vercel build

vercel deploy --prebuilt
  1. Once deployed, I promoted the deployment to Production on Vercel.

.env.production.local with NEXT_PUBLIC_BASE_URL=<app_domain> was crucial for my app to work since env.local points to localhost:3000

@jeffmlb91
Copy link

I was able to fix this by wrapping the fetch in a try/catch, like so:

try {
  const res = await fetch(_____, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' }
  });

  if (!res.ok) {
    throw new Error('Failed to fetch data');
  }

  return res.json();
} catch (e) {
  return {};
}

well yeah, I tried the same thing, doesn't break but no data is returned so nothing is rendered in the Page where I'm using that data

Same thing on my end. No error but no data is returned and nothing is rendered in the Page. And the network tab when inspecting the page shows status ok

@superiorkid
Copy link

running the npm run dev and npm run build commands together can get rid of the error.

is there a proper way to get rid of the error?

@jeffmlb91
Copy link

running the npm run dev and npm run build commands together can get rid of the error.

is there a proper way to get rid of the error?

I used npm run dev and npm run build and this issue is still persistent. No data is being returned at all

@ztanner
Copy link
Member

ztanner commented Jul 27, 2023

Hey all, as alluded to in Tim’s comment, attempting to fetch from internal API routes at build time is not supported.

The recommended way to handle this would be to perform the actual underlying server calls (ie, directly querying a database) in the component rather than attempting to fetch it externally. This will also have improved performance, since you’ll be able to avoid an extra roundtrip for when your fetch calls back to your server. See the “fetching data on the server” section of the data fetching docs for some information about this. There’s also this excellent response from a community member in our discussions forum.

As noted earlier, there’s no local API server running when you trigger a build, so there’s no underlying API to fetch, thus causing the fetch request to fail. The same is true when deploying your application: your API server will most likely not be running on localhost:3000 and so those requests will fail too. Opting the page out of static generation by setting export const dynamic = 'force-dynamic' will suppress the error by not attempting to run & cache the underlying fetch calls, but your page will no longer be statically generated.

I’ll be closing this thread as it’s by design, but please feel free to continue the conversation over in the discussions forum!

@ztanner ztanner closed this as not planned Won't fix, can't repro, duplicate, stale Jul 27, 2023
MrZhouZh added a commit to MrZhouZh/next-restful-api that referenced this issue Aug 2, 2023
@github-actions
Copy link
Contributor

This closed issue has been automatically locked because it had no new activity for a month. If you are running into a similar issue, please create a new issue with the steps to reproduce. Thank you.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Aug 15, 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. linear: next Confirmed issue that is tracked by the Next.js team. locked
Projects
None yet
Development

No branches or pull requests