Repository: nodejs/undici

Issue #1923: `UND_ERR_SOCKET` in fetch
Created: 2023-02-10T17:17:08Z
Sometimes fetch ends up with exception:
{
  cause: {
    name: "SocketError",
    code: "UND_ERR_SOCKET",
    socket: {
      localAddress: "192.168.1.33",
      localPort: 12345,
      remoteAddress: "X.Y.Z.W",
      remotePort: 443,
      remoteFamily: "IPv4",
      timeout: undefined,
      bytesWritten: 651,
      bytesRead: 441,
    },
    message: "other side closed",
    stack: "SocketError: other side closed\n    at TLSSocket.onSocketEnd (node:internal/deps/undici/undici:9499:26)\n    at TLSSocket.emit (node:events:524:35)\n    at endReadableNT (node:internal/streams/readable:1359:12)\n    at process.processTicksAndRejections (node:internal/process/task_queues:82:21)"
  },
  message: "fetch failed",
  stack: "TypeError: fetch failed\n    at Object.fetch (node:internal/deps/undici/undici:12789:11)\n    at async Object.xyzFunc..."
}

Unfortunately, we don't have a reproducible code, because of complexity of application, the initial fetch requests work, but after making some further fetch we sporadically get the error. Do you have any suggestions? Have tried all workaround found in internet, but nothing worked. The exact request which fails with node fetch, works from postman.
( Windows 11, tested results below with v19.6, however same issue happens in 18.14)

Duplicate issue #2910: Object.Fetch failed cause: other side closed
Created: 2024-03-03T04:51:45Z
I have a static site on Vercel that makes a number of fetch requests to a Strapi backend on build. It occasionally throws this error.
    at async file:///vercel/path0/dist/chunks/prerender_z0pSUssE.mjs:614:21
    at async Object.render (file:///vercel/path0/dist/chunks/astro_4VOd5ehm.mjs:1572:7)
    at async Object.renderToFinalDestination (file:///vercel/path0/dist/chunks/astro_4VOd5ehm.mjs:866:7)
    at async renderChild (file:///vercel/path0/dist/chunks/astro_4VOd5ehm.mjs:1059:5)
  Caused by:
  other side closed
    at TLSSocket.onSocketEnd (node:internal/deps/undici/undici:7998:26)
    at endReadableNT (node:internal/streams/readable:1368:12)
Error: Command "npm run build" exited with 1

It only happens occasionally and if I reploy a few times it works eventually, so I'm guessing it's not a code error. The fetch code is.
interface Props {
    endpoint: string;
    query?: string;
    wrappedByKey?: string;
    wrappedByList?: boolean;
}

/**
 * Fetches data from the Strapi API
 * @param endpoint - The endpoint to fetch from
 * @param query - The query parameters to add to the URL
 * @param wrappedByKey - The key to unwrap the response from
 * @param wrappedByList - If the response is a list, unwrap it
 * @returns
 */
export default async function fetchApi<T>({
    endpoint,
    query,
    wrappedByKey,
    wrappedByList,
}: Props): Promise<T> {
    try {
        if (endpoint.startsWith('/')) {
            endpoint = endpoint.slice(1);
        }

        const url = new URL(`${import.meta.env.STRAPI_URL}/api/${endpoint}`);
        const queryString = query ? `?${query}` : '';
        const urlWithQuery = `${url.toString()}${queryString}`;
        const res = await fetch(urlWithQuery, {
            method: "GET",
            headers: {
                Authorization: `Bearer ${import.meta.env.STRAPI_KEY}`,
                "Content-Type": "application/json",
            },
        });
        if (!res.ok) {
            throw new Error(`HTTP error! Status: ${res.status}`);
        }

        let data = await res.json();
        if (wrappedByKey) {
            data = data[wrappedByKey];
        }

        if (wrappedByList) {
            data = data[0];
        }

        return data as T;
    } catch (error) {
        // Handle errors here
        console.error("Error fetching data:", error);
        throw error; // Rethrow the error
    }
}

Closing comment (2024-03-03T05:07:03Z): Duplicate of #1923 (and others). But if this happens when you're deploying the server probably is just forcefully closing the connection, which isn't an issue related to undici.