Skip to content

HEAD method with non-zero Content-Length triggers JSON parsing error #2195

Closed
@live-small

Description

@live-small

openapi-fetch version

0.13.0

Description

HEAD method request returns 200 status code but triggers React Query's onError handler with the following error:

onError called SyntaxError: Failed to execute 'json' on 'Response': Unexpected end of JSON input

I'm not sure if this is the root cause, but looking at the code:

  1. head.test.ts only tests with Content-Length: "0" case
  2. In src/index.js, line 205-208:
// handle empty content
if (response.status === 204 || response.headers.get("Content-Length") === "0") {
  return response.ok ? { data: undefined, response } : { error: undefined, response };
}

According to RFC 9110 Section 9.3.2:

The HEAD method is identical to GET except that the server MUST NOT send content in the response. The metadata contained in the HTTP headers in response to a HEAD request SHOULD be identical to the information sent in response to a GET request.

Currently, when Content-Length is non-zero, the code attempts to parse the response body causing an error. We need to modify this to properly handle HEAD requests regardless of the Content-Length value.

Reproduction

  1. Modify head.test.ts:
    • Change Content-Length from "0" to any non-zero value (e.g., "1234")
    • Test will fail with: SyntaxError: Failed to execute 'json' on 'Response': Unexpected end of JSON input
Image
  1. Using React Query:
    "@tanstack/react-query": "^5.50.1",
const client = createClient({
  baseUrl: 'your-api-url'
});

const query = useQuery({
  queryKey: ['test'],
  queryFn: () => client.HEAD('/some-endpoint')
});

// Even with 200 response:
// - query.isError: true
// - onError is triggered with: SyntaxError: Failed to execute 'json' on 'Response': Unexpected end of JSON input

Expected result

  • HEAD method responses should not attempt body parsing
  • 200 responses should be treated as successful
  • React Query onSuccess handler should be called

Current behavior:

  • SyntaxError due to body parsing attempt
  • onError handler triggered despite successful response

Additional references:
MDN Web Docs - HEAD method

a HEAD request can read the Content-Length header to check the file size before downloading the file with a GET.

Extra

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingopenapi-fetchRelevant to the openapi-fetch library

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions