Skip to content

Cloned request asynchronously changes to bodyUsed #4150

Open
@CreativeTechGuy

Description

@CreativeTechGuy

Bug Description

If a request is cloned and the body of the cloned request is read (in a single chained instruction), after a delay the body of the original request will become "used".

Reproducible By

After some amount of time, the output will change to true for bodyUsed on the original request. Depending on the machine is how long this will take (usually within several seconds).

Note: It's intentional that the request will error so it'll keep retrying.

const request = new Request("http://localhost:1234/abc", {
    method: "POST",
    body: JSON.stringify({ a: 1 })
});

await retry(request);

async function retry(req) {
    console.log(await request.clone().text());
    for (let i = 0; i < 1000; i++) {
        console.log(i, req.bodyUsed);
        await new Promise((resolve) => setTimeout(resolve, 10));
    }
    try {
        await fetch(req.clone());
    } catch (e) {
        console.log(e);
        return await retry(req);
    }
}

The example below, which should be identical, doesn't have the issue:

const request = new Request("http://localhost:1234/abc", {
    method: "POST",
    body: JSON.stringify({ a: 1 })
});

await retry(request);

async function retry(req) {
    const clonedRequest = request.clone();
    console.log(await clonedRequest.text());
    for (let i = 0; i < 1000; i++) {
        console.log(i, req.bodyUsed);
        await new Promise((resolve) => setTimeout(resolve, 10));
    }
    try {
        await fetch(req.clone());
    } catch (e) {
        console.log(e);
        return await retry(req);
    }
}

Expected Behavior

A cloned request wouldn't affect the original, and the code style shouldn't affect the behavior.

Logs & Screenshots

N/A

Environment

Reproducible on Node 23.11.0 and 22.14.0 (haven't tried others but I assume other versions have a similar problem).

Additional context

This can be reproduced on multiple machines with multiple OSes with multiple Node versions. The amount of iterations seems "random" per machine, but once you see how long it takes on your machine to magically change, it'll be pretty consistently reproducible in the same amount of time each time you re-run.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions