Skip to content

Incorrect caching of requests using URLSearchParams as body #68

@fugidev

Description

@fugidev

Example (adapted from https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#setting_a_body):

Fetch("https://example.com", {
  fetchOptions: {
    method: "POST",
    body: new URLSearchParams({ query: 'abc' }),
  },
})

Any change in the URLSearchParams will hit the same cache entry, which should not happen.

This happens because JSON.stringify (used here) serializes any URLSearchParams object to {}, because URLSearchParams does not implement a toJSON method. A solution could be to implement a replacer for JSON.stringify.

As a workaround, one can manually convert it to its string representation and set the Content-Type header (as undici's implementation would do automatically in the first example):

let params = new URLSearchParams({ query: 'abc' });

Fetch("https://example.com", {
  fetchOptions: {
    method: "POST",
    body: params.toString(),
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
    },
  },
})

Note: as mentioned in the MDN article, URLSearchParams is not the only kind of object one can pass as body, apart from a plain string. I only tested URLSearchParams.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions