next.js: Using Undici as node fetch polyfill causes fetch failed

Verify canary release

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

Provide environment information

N/A

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/vercel/next.js/blob/e601a3b53292278e1b7d1ef1f692ed340ef8be10/packages/next/src/server/node-polyfill-fetch.ts#L6

To Reproduce

Ensure project is using serverless functions that are from the frankfurt network (so far I know this one causes the problem, but maybe others do as well) image

Below are my steps, but they should be entirely optional since replicating this is possible in different ways.

  1. have a next api endpoint that fires a tRCP call using tRPC’s client

  2. call the endpoint

  3. observe that fetch failed because of undici (node fetch polyfill)

Describe the Bug

Big thanks to TillaTheHun0 for reporting this.

I want to make a bug report since I replicated and can confirm his thesis.

Next has a node polyfill for fetch, which uses either undici or node-fetch depending on an environment variable called __NEXT_USE_UNDICI. This env variable is likely set by Vercel depending on which network the Serverless Functions are configured to execute on.

I tested countless times, and the thing that solved my problems was indeed changing the network location of my serverless functions in my Project Settings on Vercel.

Undici currently has some issue (RequestContentLengthMismatchError), partially documented here. This issue is causing all sorts of problems from different places since this fetch polyfill is used by many other tools.

In my case it was tRPC complaining, with:

 TRPCClientError: fetch failed
    at TRPCClientError.from (file:///var/task/node_modules/@trpc/client/dist/transformResult-6fb67924.mjs:13:16)
    at file:///var/task/node_modules/@trpc/client/dist/links/httpBatchLink.mjs:211:64 {
  meta: undefined,
  shape: undefined,
  data: undefined,
  [cause]: TypeError: fetch failed
      at Object.fetch (node:internal/deps/undici/undici:14062:11) {
    cause: RequestContentLengthMismatchError: Request body length does not match content-length header
        at AsyncWriter.end (node:internal/deps/undici/undici:9704:19)
        at writeIterable (node:internal/deps/undici/undici:9614:16) {
      code: 'UND_ERR_REQ_CONTENT_LENGTH_MISMATCH'
    }
  }
}

though I read around different places people encountering the same problem in various ways.

We should either use only one polyfill (the working one) while waiting for undici to be patched, or we should allow people to explicitly choose which polyfill they’d like through configuring __NEXT_USE_UNDICI somewhere. Though I have a feeling that going with either option could be impossible if there’s unknown limitations to the machine running the Functions that make it so undici is chosen over node-fetch.

Regardless, it is currently a fact that the “Project Settings” > “Functions” page (on Vercel) does not have any information about this behaviour. At the very least we should inform users that there’s environment variables that could change depending on the chosen region for the Serverless Functions. Optimally we should provide a list with environment variables and their configuration for the different regions, and ideally also how these map to certain behaviours. At the very least this would speed up debugging and problem solving IMO. (this part might not be specific to the Next repo though)

Expected Behavior

fetch requests should not fail like this, regardless of which serverless function they are running on.

Which browser are you using? (if relevant)

N/A

How are you deploying your application? (if relevant)

N/A

About this issue

  • Original URL
  • State: closed
  • Created a year ago
  • Reactions: 19
  • Comments: 34 (5 by maintainers)

Most upvoted comments

I’ m also seeing this error, but it seems to be in the context of a server action failing to redirect.

I have a server action that does this:

'use server'

export async function exampleAction() {
    const token = getToken(headers())

    await asyncFunction(...)

    redirect('/some-path')
}

Which throws:

failed to get redirect response TypeError: fetch failed
    at Object.fetch (node:internal/deps/undici/undici:11457:11) {
  cause: RequestContentLengthMismatchError: Request body length does not match content-length header
      at write (<app>/node_modules/next/dist/compiled/undici/index.js:1:67105)
      at _resume (<app>/node_modules/next/dist/compiled/undici/index.js:1:66726)
      at resume (<app>/node_modules/next/dist/compiled/undici/index.js:1:65413)
      at connect (<app>/node_modules/next/dist/compiled/undici/index.js:1:65301) {
    code: 'UND_ERR_REQ_CONTENT_LENGTH_MISMATCH'
  }
}

I have an inbound PR that fixes it

https://github.com/vercel/next.js/pull/53843

I started to see this too in server actions

  async function handleForm(formData: FormData) {
    'use server';
    const { error } = await updateProject(projectId, formData);

    const errorParam = error ? `&errorMessage=${error}` : '';
    redirect(`/projects/${projectId}/edit?tab=edit${errorParam}`);
  }
failed to get redirect response TypeError: fetch failed
    at Object.fetch (node:internal/deps/undici/undici:11522:11) {
  cause: RequestContentLengthMismatchError: Request body length does not match content-length header
      at write (/app/node_modules/next/dist/compiled/undici/index.js:1:67105)
      at _resume (/app/node_modules/next/dist/compiled/undici/index.js:1:66726)
      at resume (/app/node_modules/next/dist/compiled/undici/index.js:1:65413)
      at connect (/app/node_modules/next/dist/compiled/undici/index.js:1:65301) {
    code: 'UND_ERR_REQ_CONTENT_LENGTH_MISMATCH'
  }
}

content-length is 2 on the response but body is empty

Screenshot 2023-07-08 at 06 25 41

I ran into this same issue when using redirect() inside a server action. I walked through a few Next versions to see where I would get the fix. I was finally able to solve this by downgrading Next as follows:

- "next": "^13.4.12",
+ "next": "13.4.7",

I have tested this fix with the development server inside a node:latest (v20.5.0) docker container and I am no longer runing into the error.

Any known workaround for this?

This started for me today too on 13.4.13

I’m facing the same issue here

I am also seeing the same issue when redirecting to a page from a server action

I’m having the same issue as well.

I’m having the same issue with a redirect inside a server action

In my case this happened when the server’s content type header is not what actually is. For example the content type says it’s gzip but the content is without compression, thus causing the decompression failed.

To exclude/verify if this is your case, you can add this header temporarily and try again:

"Accept-Encoding": "identity",

Seeing lots of undici issues across multiple projects on latest next and latest node 18:

Node.js v18.17.1
Static worker unexpectedly exited with code: 1 and signal: null
[    ] - info Generating static pages (3/9)node:internal/process/promises:288
            triggerUncaughtException(err, true /* fromPromise */);
            ^

TypeError: terminated
    at Fetch.onAborted (node:internal/deps/undici/undici:11442:53)
    at Fetch.emit (node:events:514:28)
    at Fetch.terminate (node:internal/deps/undici/undici:10695:14)
    at Object.onError (node:internal/deps/undici/undici:11537:36)
    at Request.onError (node:internal/deps/undici/undici:8310:31)
    at errorRequest (node:internal/deps/undici/undici:10378:17)
    at Socket.onSocketClose (node:internal/deps/undici/undici:9811:9)
    at Socket.emit (node:events:514:28)
    at TCP.<anonymous> (node:net:323:12)
    at TCP.callbackTrampoline (node:internal/async_hooks:130:17) {
  [cause]: Error: write EPIPE
      at WriteWrap.onWriteComplete [as oncomplete] (node:internal/stream_base_commons:94:16)
      at WriteWrap.callbackTrampoline (node:internal/async_hooks:130:17)
}

Node.js v18.17.1
node:internal/deps/undici/undici:11576
    Error.captureStackTrace(err, this);
          ^

TypeError: fetch failed
    at Object.fetch (node:internal/deps/undici/undici:11576:11) {
  cause: Error: write EPIPE
      at WriteWrap.onWriteComplete [as oncomplete] (node:internal/stream_base_commons:94:16)
      at WriteWrap.callbackTrampoline (node:internal/async_hooks:130:17) {
    errno: -32,
    code: 'EPIPE',
    syscall: 'write'
  }
}

Same issue here. Works on 13.4.7 but not on 13.4.13 (using signIn function from next-auth on a custom login page).

Also having this issue in the redirect. I’ve created a reproduction here https://github.com/wladiston/reproduction-next-fetch-bug

It seems like if I pin next to 13.4.7 the error goes away.

Ran into similar issues - weirdly enough in iad1 Washington. After some googling, I stumbled across this article which recommended using fetch-ponyfill'. This fixed the issue for me.

I wrote that, you’re welcome 😃)

Ran into similar issues - weirdly enough in iad1 Washington. After some googling, I stumbled across this article which recommended using fetch-ponyfill'. This fixed the issue for me.

@julioxavierr using node-fetch solves this problem, but unfortunately it doesn’t fit well as next fetch do.

+1 to this. I’m on 14.0.5-canary and getting this error on Vercel during build.

I’m using Apollo Client Nextjs for useSuspenseQuery() / rsc query in static pages and the error happens during build when pre-rendering the page.

This error doesn’t happen in local dev env.

ApolloError: fetch failed
--
20:39:09.889 | at new ApolloError (/vercel/path0/app/.next/server/chunks/7756.js:120721:28)
20:39:09.889 | at /vercel/path0/app/.next/server/chunks/7756.js:120181:19
20:39:09.890 | at both (/vercel/path0/app/.next/server/chunks/7756.js:124244:53)
20:39:09.890 | at /vercel/path0/app/.next/server/chunks/7756.js:124237:72
20:39:09.890 | at new Promise (<anonymous>)
20:39:09.890 | at Object.then (/vercel/path0/app/.next/server/chunks/7756.js:124237:24)
20:39:09.890 | at Object.error (/vercel/path0/app/.next/server/chunks/7756.js:124245:49)
20:39:09.890 | at notifySubscription (/vercel/path0/app/.next/server/chunks/7756.js:93242:18)
20:39:09.890 | at onNotify (/vercel/path0/app/.next/server/chunks/7756.js:93281:3)
20:39:09.890 | at SubscriptionObserver.error (/vercel/path0/app/.next/server/chunks/7756.js:93342:7) {
20:39:09.890 | graphQLErrors: [],
20:39:09.890 | protocolErrors: [],
20:39:09.890 | clientErrors: [],
20:39:09.890 | networkError: TypeError: fetch failed
20:39:09.890 | at Object.fetch (/vercel/path0/app/node_modules/next/dist/compiled/undici/index.js:1:26669) {
20:39:09.890 | cause: RequestContentLengthMismatchError: Request body length does not match content-length header
20:39:09.890 | at AsyncWriter.end (/vercel/path0/app/node_modules/next/dist/compiled/undici/index.js:1:71966)
20:39:09.890 | at writeIterable (/vercel/path0/app/node_modules/next/dist/compiled/undici/index.js:1:70638) {
20:39:09.890 | code: 'UND_ERR_REQ_CONTENT_LENGTH_MISMATCH'
20:39:09.890 | }
20:39:09.890 | },
20:39:09.891 | extraInfo: undefined
20:39:09.891 | }