upstash/context7 · error · Context7JSONParseError
invalid_json_response
invalid_json_response
Error message
Unable to parse response body: ${truncatedBody} What it means
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.
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.
Example fix
// before
const client = new Context7({ baseUrl: 'https://context7.com' }); // dashboard URL returns HTML
// after
const client = new Context7({ baseUrl: 'https://api.context7.com', apiKey: process.env.CONTEXT7_API_KEY }); Defensive patterns
Strategy: try-catch
Validate before calling
// verify endpoint returns JSON before wiring the client
const probe = await fetch(baseUrl + '/health');
if (!(probe.headers.get('content-type') || '').includes('application/json')) throw new Error('baseUrl does not serve JSON'); Try / catch
try {
return await client.libraryDocs(...);
} catch (e) {
if (e.code === 'invalid_json_response') {
console.error('Non-JSON body from API:', e.message); // includes truncated body
// fall back or alert; check status/auth/baseUrl
}
throw e;
} Prevention
- 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.
When it happens
Trigger: 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.
Common situations: 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.
Understand the failure class
Background: "Invalid JSON response" and "Failed to parse response" errors: when an API answers 200 but the body isn't the JSON your library expected — this error's family across 28 libraries.
- Parsing and encoding errors: unexpected token, malformed input — why parsers reject input and how to find the real culprit.
Related errors
- errorBody.error || errorBody.message || res.statusText
- Failed to fetch user info
- ( )
- HTTP from /api/auth/mcp
- Invalid response from
AI-assisted analysis of upstash/context7@4416fb855b (2026-09-16).
Data as JSON: /api/errors/5c3274384fa80ece.
Report an issue: GitHub.
Appendix: source
Thrown at packages/sdk/src/http/response.ts:73
metadata: Context7ResponseMetadata,
retryable: boolean
): Promise<never> {
const rawBody = await response.text();
let errorBody: { error?: string; message?: string } = {};
if (rawBody) {
try {
const parsed: unknown = JSON.parse(rawBody);
if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
const { error, message } = parsed as Record<string, unknown>;
errorBody = {
error: typeof error === "string" ? error : undefined,
message: typeof message === "string" ? message : undefined,
};
}
} catch (cause) {
if (response.headers.get("content-type")?.includes("application/json")) {
throw jsonParseError(rawBody, metadata, cause, retryable);
}
}
}
throw new Context7Error(errorBody.message || errorBody.error || response.statusText, {
code: errorBody.error ?? "http_error",
status: response.status,
requestId: metadata.requestId,
rateLimit: metadata.rateLimit,
retryable,
});
}
async function parseJson(response: Response, metadata: Context7ResponseMetadata): Promise<unknown> {
const rawBody = await response.text();
try {
return JSON.parse(rawBody);
} catch (cause) {View on GitHub (pinned to 4416fb855b)