Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 220
Berk Cohadar Avatar asked Dec 19 '25 03:12

Berk Cohadar


1 Answers

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.

like image 129
TheFlyBiker 420 Avatar answered Dec 21 '25 23:12

TheFlyBiker 420



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!