denoland/deno · error · TypeError

Response body is already used

Error message

Response body is already used

What it means

Cache.put(request, response) requires the response body to be unread (spec step 8 checks innerResponse.body.unusable()). put() consumes the stream itself when storing, so a body that was already read, piped, or locked by a reader is rejected.

Solutions

  1. Clone before reading: `await cache.put(req, res.clone())`, then consume the original
  2. Or read from the clone and cache the untouched response
  3. Check `res.bodyUsed === false` before calling cache.put

Example fix

// before
const text = await res.text();
await cache.put(req, res); // body already used -> throws

// after
await cache.put(req, res.clone());
const text = await res.text();
Defensive patterns

Strategy: validation

Validate before calling

if (response.bodyUsed) {
  // body already consumed: clone earlier, or cache a fresh fetch
}

Prevention

When it happens

Trigger: `await res.text(); cache.put(req, res)`; calling res.json() before cache.put; obtaining a reader from res.body and then passing the response to cache.put.

Common situations: Logging or inspecting a response before caching it; routing the same Response object to both a render path and a cache path.

Related errors


AI-assisted analysis of denoland/deno@9ad36f7a2c (2026-08-20). Data as JSON: /api/errors/2d90a3036614a59b. Report an issue: GitHub.

Appendix: source

Thrown at ext/cache/01_cache.js:176

    // Step 6.
    if (innerResponse.status === 206) {
      throw new TypeError("Response status must not be 206");
    }
    // Step 7.
    const varyHeader = getHeader(innerResponse.headerList, "vary");
    if (varyHeader) {
      const fieldValues = StringPrototypeSplit(varyHeader, ",");
      for (let i = 0; i < fieldValues.length; ++i) {
        const field = fieldValues[i];
        if (StringPrototypeTrim(field) === "*") {
          throw new TypeError("Vary header must not contain '*'");
        }
      }
    }

    // Step 8.
    if (innerResponse.body !== null && innerResponse.body.unusable()) {
      throw new TypeError("Response body is already used");
    }

    const stream = innerResponse.body?.stream;
    let rid = null;
    if (stream) {
      const resourceBacking = getReadableStreamResourceBacking(
        innerResponse.body?.stream,
      );
      if (resourceBacking) {
        rid = resourceBacking.rid;
      } else {
        rid = resourceForReadableStream(stream, innerResponse.body?.length);
      }
    }

    // Remove fragment from request URL before put.
    reqUrl.hash = "";

View on GitHub (pinned to 9ad36f7a2c)