If your NextJS App Router app is throwing this error:

UND_ERR_REQ_CONTENT_LENGTH_MISMATCH 

Then it’s likely that you are using fetch which is the standard option for making HTTP requests. There was an open issue for using Fetch within NextJS since NextJS wraps the default fetch with their own implementation. To help isolate this issue, we replaced fetch with axios, and it resolved the errors!

Dealing with errors is a part of life when you are a coder

Undici is the underlying name of fetch() in Node, which explains the UND part of the error message.

To resolve this issue, just use a different HTTP client, such as:

  1. Axios
  2. Got
  3. SuperAgent

Here is the default fetch in NextJS:

var requestOptions: RequestInit = {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
text: text,
}),
redirect: "follow",
};

const apiUrl = `${baseUrl}/api/yourApi/`;

try {
let res = await fetch(apiUrl, requestOptions);
const responseData = await res.json();
return responseData;
} catch (error) {
console.error("Error during fetch:", error);
throw error; // Re-throw to handle it accordingly
}

Here is the same code using Axios

  try {
const response = await axios.post(
`${baseUrl}/api/yourApi/`,
{
text: text,
},
{
headers: {
"Content-Type": "application/json",
},
},
);
return response. Data;
} catch (error) {
console.error(error);
}

In addition to resolving the UND_ERR_REQ_CONTENT_LENGTH_MISMATCH error, it Axios provides other benefits:

Axios Benefits

  • You don’t have to stringify the body. This is error prone typically, so axios deals with it for you.
  • Dedicated method for `get`, `post`, etc., so it’s less likely to make mistakes compared fetch which just specifies the method value as a string POST
  • Don’t need to call res.json() , instead you can just access your data as needed, i.e. response.data.yourData

See Also

  1. Using Undici as node fetch polyfill causes fetch failed · Issue #48744 · vercel/next.js (github.com)
  2. reactjs — NextJS fails with UND_ERR_REQ_CONTENT_LENGTH_MISMATCH after redirect from server — Stack Overflow

--

--

janac

Most of my writing is about software. I enjoy summarizing and analyzing books and self-help videos. I am senior software consultant at LazerTechnologies.com.