{"record":{"id":"5c3274384fa80ece","repo":"upstash/context7","slug":"invalid-json-response","errorCode":"invalid_json_response","errorMessage":"Unable to parse response body: ${truncatedBody}","messagePattern":"Unable to parse response body: (.+?)","errorType":"exception","errorClass":"Context7JSONParseError","httpStatus":null,"severity":"error","filePath":"packages/sdk/src/http/response.ts","lineNumber":73,"sourceCode":"  metadata: Context7ResponseMetadata,\n  retryable: boolean\n): Promise<never> {\n  const rawBody = await response.text();\n  let errorBody: { error?: string; message?: string } = {};\n\n  if (rawBody) {\n    try {\n      const parsed: unknown = JSON.parse(rawBody);\n      if (typeof parsed === \"object\" && parsed !== null && !Array.isArray(parsed)) {\n        const { error, message } = parsed as Record<string, unknown>;\n        errorBody = {\n          error: typeof error === \"string\" ? error : undefined,\n          message: typeof message === \"string\" ? message : undefined,\n        };\n      }\n    } catch (cause) {\n      if (response.headers.get(\"content-type\")?.includes(\"application/json\")) {\n        throw jsonParseError(rawBody, metadata, cause, retryable);\n      }\n    }\n  }\n\n  throw new Context7Error(errorBody.message || errorBody.error || response.statusText, {\n    code: errorBody.error ?? \"http_error\",\n    status: response.status,\n    requestId: metadata.requestId,\n    rateLimit: metadata.rateLimit,\n    retryable,\n  });\n}\n\nasync function parseJson(response: Response, metadata: Context7ResponseMetadata): Promise<unknown> {\n  const rawBody = await response.text();\n  try {\n    return JSON.parse(rawBody);\n  } catch (cause) {","sourceCodeStart":55,"sourceCodeEnd":91,"githubUrl":"https://github.com/upstash/context7/blob/4416fb855b8f752be735e34f943b5d0762701aad/packages/sdk/src/http/response.ts#L55-L91","documentation":"throwResponseError builds a Context7Error with code \"invalid_json_response\" when the HTTP response body cannot be parsed into the expected JSON error/success shape. The message includes a truncated copy of the raw body so you can see what the server actually returned. It means the server responded, but not with the JSON the SDK expects.","triggerScenarios":"The API returns a non-JSON body (HTML error page, empty body, plain text) with a non-2xx or unexpected status, and parsing the body as JSON throws inside response handling; if content-type is application/json but the body is malformed, a jsonParseError is thrown instead.","commonSituations":"Hitting a proxy/login page that returns HTML; server-side 502/504 gateway pages; wrong baseUrl pointing at a non-API endpoint; API version drift changing the response shape; auth redirect pages.","solutions":["Read the truncatedBody in the message to see what the server returned and fix the request accordingly.","Verify baseUrl points at the Context7 API endpoint, not a proxy or dashboard URL.","Check authentication — HTML login/error pages usually indicate missing or invalid credentials.","Check for API version changes or gateway errors (502/504) and retry later if upstream is degraded.","Log response status and content-type to confirm whether the server intends to return JSON."],"exampleFix":"// before\nconst client = new Context7({ baseUrl: 'https://context7.com' }); // dashboard URL returns HTML\n// after\nconst client = new Context7({ baseUrl: 'https://api.context7.com', apiKey: process.env.CONTEXT7_API_KEY });","handlingStrategy":"try-catch","validationCode":"// verify endpoint returns JSON before wiring the client\nconst probe = await fetch(baseUrl + '/health');\nif (!(probe.headers.get('content-type') || '').includes('application/json')) throw new Error('baseUrl does not serve JSON');","typeGuard":null,"tryCatchPattern":"try {\n  return await client.libraryDocs(...);\n} catch (e) {\n  if (e.code === 'invalid_json_response') {\n    console.error('Non-JSON body from API:', e.message); // includes truncated body\n    // fall back or alert; check status/auth/baseUrl\n  }\n  throw e;\n}","preventionTips":["Point baseUrl at the API host, never a dashboard or marketing site.","Send valid credentials to avoid HTML login/error interstitials.","Monitor for gateway errors (502/504) that return HTML pages.","Pin/track SDK versions compatible with the API version you call.","Log status + content-type on failures for faster diagnosis."],"tags":["http","json","response-parsing","api"],"backgroundTag":"invalid-json-response","analyzedSha":"4416fb855b8f752be735e34f943b5d0762701aad","analyzedAt":"2026-09-16T20:28:07.148Z","contentChangedAt":"2026-09-16T20:28:07.148Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}