Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my fetch fail when using getServerSideProps in Next.js?

I have tried fetch and it works fine with swapi.dev, but when I do this, it errors. All I am doing is passing the request down to the fetch function, with the appropriate headers, to do my authentication checks before a page is rendered.

export async function getServerSideProps({ req }) {
  try {
    const res = await fetch(`${process.env.NEXT_PUBLIC_BACKEND_URL}/api/user`, {
      credentials: "include",
      headers: {
        "Access-Control-Allow-Credentials": true,
        "X-Requested-With": "XMLHttpRequest",
        ...req.headers,
      },
    });

    console.log(res);

    const data = await res.json();
    return { props: { data } };
  } catch (error) {
    console.log(error);
    return { props: { data: [] } };
  }
  
}
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) {
  cause: Error: [object Object]
      at makeNetworkError (node:internal/deps/undici/undici:6317:51)
      at httpNetworkFetch (node:internal/deps/undici/undici:7810:16)
      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
  }
}
like image 272
Ali Gajani Avatar asked Dec 17 '25 15:12

Ali Gajani


1 Answers

Getting the same issue in node 18 version, worked for me with node v14.19.1

like image 80
Somit Garhewal Avatar answered Dec 20 '25 06:12

Somit Garhewal



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!