Skip to content

Commit 85ba07a

Browse files
committed
Fix body reading in logging middleware for non-JSON responses
The logging middleware was calling response.json() and falling back to response.text() on the same cloned response. This fails when json() fails to parse (e.g., HTML error pages from Cloudflare) because json() consumes the body stream even when parsing fails. Fix: Read as text() first, then try JSON.parse() on the string. This only consumes the body once and handles non-JSON responses correctly.
1 parent 2b4e60a commit 85ba07a

1 file changed

Lines changed: 6 additions & 2 deletions

File tree

packages/b2c-tooling-sdk/src/clients/middleware.ts

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -165,10 +165,14 @@ export function createLoggingMiddleware(config?: string | LoggingMiddlewareConfi
165165

166166
const clonedResponse = response.clone();
167167
let responseBody: unknown;
168+
// Read as text first, then try to parse as JSON.
169+
// This avoids a bug where json() consumes the body stream even when parsing fails,
170+
// making subsequent text() calls fail with "Body has already been read".
171+
const text = await clonedResponse.text();
168172
try {
169-
responseBody = await clonedResponse.json();
173+
responseBody = JSON.parse(text);
170174
} catch {
171-
responseBody = await clonedResponse.text();
175+
responseBody = text;
172176
}
173177

174178
// Mask sensitive/large body keys before logging

0 commit comments

Comments
 (0)