UND_ERR_REQ_CONTENT_LENGTH_MISMATCH
Answered
Transvaal lion posted this in #help-forum
Transvaal lionOP
I'm building an application with NextJS 14.2 app directory with the incorporation of Supabase.
I have a custom fetchWrapper function and because of the supabase ssr authentication I'm passing in headers from next/headers to the fetch requests.
The GET request work perfectly but when I try to do POST request I'm getting an error: cause: _RequestContentLengthMismatchError: Request body length does not match content-length header (I've also provided the error in a screenshot)
I'm using Route handlers instead of server actions because I want to use the power of revalidation to make everything real-time.
on the third screenshot I've also provided the usage of my custom fetchWrapper function.
how can I fix this error?
I have a custom fetchWrapper function and because of the supabase ssr authentication I'm passing in headers from next/headers to the fetch requests.
The GET request work perfectly but when I try to do POST request I'm getting an error: cause: _RequestContentLengthMismatchError: Request body length does not match content-length header (I've also provided the error in a screenshot)
I'm using Route handlers instead of server actions because I want to use the power of revalidation to make everything real-time.
on the third screenshot I've also provided the usage of my custom fetchWrapper function.
how can I fix this error?
Answered by Transvaal lion
import { headers as nextHeaders } from "next/headers";
const baseURL = process.env.API_URL || process.env.NEXT_PUBLIC_API_URL;
interface FetchWrapperOptions extends RequestInit {
body?: any;
}
const fetchWrapper = async <T>(
endpoint: string,
options: FetchWrapperOptions = {}
): Promise<Response> => {
const url = `${baseURL}${endpoint}`;
// Convert next/headers to a plain object
const defaultHeaders = Object.fromEntries(nextHeaders().entries());
const filteredHeaders = Object.fromEntries(
Object.entries(defaultHeaders).filter(([key]) => key.toLowerCase() !== "content-length")
);
// Merge headers with any additional headers provided in options
const finalHeaders: Record<string, string> = {
...filteredHeaders,
...(options.headers ? Object.fromEntries(new Headers(options.headers).entries()) : {}),
};
let body: any = options.body;
if (body && typeof body === "object" && !(body instanceof FormData)) {
body = JSON.stringify(body);
finalHeaders["Content-Type"] = "application/json";
}
const finalOptions: RequestInit = { ...options, headers: finalHeaders, body };
try {
const response = await fetch(url, finalOptions);
if (!response.ok) {
const errorData = await response.json();
console.log("Error Data:", errorData);
throw new Error(errorData.message || "Something went wrong");
}
return response;
} catch (error) {
console.error("Fetch error:", error);
throw error;
}
};
export default fetchWrapper;I finally fixed this error by filtering the default headers and removing the content-length, letting the fetch function handle automatically setting it
1 Reply
Transvaal lionOP
import { headers as nextHeaders } from "next/headers";
const baseURL = process.env.API_URL || process.env.NEXT_PUBLIC_API_URL;
interface FetchWrapperOptions extends RequestInit {
body?: any;
}
const fetchWrapper = async <T>(
endpoint: string,
options: FetchWrapperOptions = {}
): Promise<Response> => {
const url = `${baseURL}${endpoint}`;
// Convert next/headers to a plain object
const defaultHeaders = Object.fromEntries(nextHeaders().entries());
const filteredHeaders = Object.fromEntries(
Object.entries(defaultHeaders).filter(([key]) => key.toLowerCase() !== "content-length")
);
// Merge headers with any additional headers provided in options
const finalHeaders: Record<string, string> = {
...filteredHeaders,
...(options.headers ? Object.fromEntries(new Headers(options.headers).entries()) : {}),
};
let body: any = options.body;
if (body && typeof body === "object" && !(body instanceof FormData)) {
body = JSON.stringify(body);
finalHeaders["Content-Type"] = "application/json";
}
const finalOptions: RequestInit = { ...options, headers: finalHeaders, body };
try {
const response = await fetch(url, finalOptions);
if (!response.ok) {
const errorData = await response.json();
console.log("Error Data:", errorData);
throw new Error(errorData.message || "Something went wrong");
}
return response;
} catch (error) {
console.error("Fetch error:", error);
throw error;
}
};
export default fetchWrapper;I finally fixed this error by filtering the default headers and removing the content-length, letting the fetch function handle automatically setting it
Answer