Next.js 13 - Fetch Failed Error. How do I resolve this?
Asked Answered
N

4

17

I was trying the Next 13 beta version, and I faced a strange problem. What I am trying to do is, fetch data on the server side and display them on the page. However, the "fetch" operation fails on the server side. Below is the code for the Next.js page. It falls under the 'app' directory, as 'app/pageName/page.js'

import React from 'react'

async function callApi() {
  const data = await fetch('https://api-psepeti.herokuapp.com/api/items/?search=yil');
  return data.json();
}

export default async function Page() {
  const data = await callApi();
  return (
    <main>
        {data.results && data.results.map((product, index) => (
          <h1>{product.title}</h1>
        ))}
    </main>
  )
}

Click to see Error Message. (UND_ERR_CONNECT_TIMEOUT)

Click to see API response (Django REST)

Click to see Next 13 Doc

Note: The fetch operation fails after ~ 10 seconds.

What I did:

  • I tried Axios, but it also fails.
  • I tried adding 'enableUndici: true' to the next config file. (Fails)
  • I tried other mock APIs, some work some don't. (Weird)
  • They all work normally on the client side.
  • They all work normally in the Next 12.
  • They all work normally on any other React app.

Versions:

  • node 18.12.0
  • next 13.1.0
  • react 18.2.0
  • react-dom 18.2.0
  • npm 9.2.0

OS: M1 IOS (Ventura 13.1)

Next config.js:

const nextConfig = {
  experimental: {
    appDir: true,
    enableUndici: true
  },
}

module.exports = nextConfig

PS: The tricky part is everything works well with Next 12, but not Next 13. When we do the same operations in Next12 using getStaticProps and getServerSideProps, it works just fine.

Nierman answered 13/12, 2022 at 3:31 Comment(7)
It's working fine for me your code.Hardboard
@yousoumar do you use Next 13?Nierman
Yes: "next": "13.0.6", "react": "18.2.0", "react-dom": "18.2.0".Hardboard
@yousoumar I use the same versions. I tried another computer but had the same error. When I try a different API service, this code works. So the problem is not about the code. At the same time, when I call the same API endpoint on the client side, it also works. So, the problem is not about the API service as well. I am so confused.Nierman
I have the same problem and everything is up to date, this is weirdGonna
did you add any content security policy in your next.config?Cornflakes
Did u fix you problem? This is my issue right now😭Airlift
D
1

The error should be ok, tried your request in the browser:

(Update: here was the old server url which you provided and wasn't available for me, meanwhile my browser claims it's a 'security risk' so I completely removed that link here...)

returns "unable to connect" which means there should be an error.

In general you have to wrap all the await with a try/catch to avoid unhandled errors, will give you a bit more accurate information I assume.

try{
  /* await here */
} catch(error: any|unknown){
  /* handle error */
}

additionally: I get that dev's like axio, however fetch is already integrated, so I try to avoid adding another library doing the same like an existing one.

Dareece answered 31/3, 2023 at 13:44 Comment(4)
Hi @faebster, the above domain was reachable at the time of this question. But then we moved our server to another domain. However, the error still seems to be there for some reason. The tricky part is everything works well with Next 12. When we update to 13, server-side data fetches just don't work. More specifically, we do the same operations using getStaticProps and getServerSideProps, it works just fine. PS: I updated the domain please take another look.Nierman
@BerkCohadar sorry for late reply. I assume it's been solved meanwhile?Dareece
@BerkCohadar is your fetch code inside a app/page.tsx file? if you use it outside it will use native fetch which is not Next fetch... same error when adding { cache: "no-store" } as 2nd argument in .fetch ?? However if so I'd expect a Hydration error. But better to ask than to assume (sorry just seen it is a app page. I leave the comment for others)Dareece
there are many reasons why a fetch could fail, one workaround could be to put the fetch into app/api directory and fetch server-side. Then you call your api method to get the results, it's anyway cleaner IMO, you could e.g. fail only client-side due to CORS when using SSR as it will fetch server&clientside. you can check this by using isOnServer hook and SSRProvider from react-area (Adobe). The error you receive is just not good enough, so first approach check network tab for details.ry it in app/api/ hen cisOnServk if it works either server or cliemaybe we can get closer to the real issueDareece
M
1

I think you might need to wait for .json() as well:

    async function callApi() {
      const data = await fetch('https://api-psepeti.herokuapp.com/api/items/?search=yil');
      let result = await data.json();
      return resut;
    }

I hope it works

Maharaja answered 20/4, 2023 at 19:34 Comment(0)
P
1

I too, was facing this issue but only on localhost. Turns out it's because Node17/18 is using ipv6 as default for localhost.

Option 1:

Change it to ipv4first by doing the following in next.config.mjs:

import dns from "dns";

dns.setDefaultResultOrder("ipv4first");

Option 2:

You can fetch using 127.0.0.1 instead of localhost in the fetch URL

Source

Look at this Github Comment.

The problem is because of the localhost in the fetch URL which Nodejs fails to recognize.

Photoengraving answered 18/12, 2023 at 15:57 Comment(0)
D
0

So I've resolved my issue by creating this small script and attaching that to the next build (ofc install undici beforehand)

const { setGlobalDispatcher, EnvHttpProxyAgent } = require('undici');

// sets proxy user from env variables
if (process.env.HTTPS_PROXY || process.env.HTTP_PROXY) {
  console.log('Using proxy user:', process.env.HTTP_PROXY || process.env.HTTPS_PROXY);
  console.log('Setting no_proxy to:', process.env.NO_PROXY);
  setGlobalDispatcher(new EnvHttpProxyAgent());
}

and attaching it to the build in package.json

"build": "node -r './proxy_fixer' node_modules/next/dist/bin/next build",
Drus answered 30/7 at 15:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.