{"record":{"id":"8a73e00a29f2ea5b","repo":"jackwener/OpenCLI","slug":"instagram-private-publish-configure-sidecar-return","errorCode":null,"errorMessage":"Instagram private publish configure_sidecar returned invalid JSON","messagePattern":"Instagram private publish configure_sidecar returned invalid JSON","errorType":"exception","errorClass":"CommandExecutionError","httpStatus":null,"severity":"error","filePath":"clis/instagram/_shared/private-publish.js","lineNumber":854,"sourceCode":"async function publishSidecarWithRetry(input) {\n    const waitMs = input.waitMs ?? sleep;\n    const requestInit = {\n        method: 'POST',\n        headers: {\n            ...buildPrivateApiHeaders(input.apiContext),\n            'Content-Type': 'application/json',\n        },\n        body: JSON.stringify(input.payload),\n    };\n    for (let attempt = 0; attempt < INSTAGRAM_PRIVATE_SIDECAR_TRANSCODE_ATTEMPTS; attempt += 1) {\n        const response = await input.fetcher('https://www.instagram.com/api/v1/media/configure_sidecar/', requestInit);\n        const text = await response.text();\n        let json = {};\n        try {\n            json = text ? JSON.parse(text) : {};\n        }\n        catch {\n            throw new CommandExecutionError('Instagram private publish configure_sidecar returned invalid JSON');\n        }\n        if (!response.ok) {\n            const detail = text ? ` ${text.slice(0, 500)}` : '';\n            throw new CommandExecutionError(`Instagram private publish configure_sidecar failed: ${response.status}${detail}`);\n        }\n        const message = String(json?.message || '');\n        if (response.status === 202\n            || /transcode not finished yet/i.test(message)) {\n            if (attempt >= INSTAGRAM_PRIVATE_SIDECAR_TRANSCODE_ATTEMPTS - 1) {\n                throw new CommandExecutionError('Instagram private publish configure_sidecar timed out waiting for video transcode', text.slice(0, 500));\n            }\n            await waitMs(INSTAGRAM_PRIVATE_SIDECAR_TRANSCODE_WAIT_MS);\n            continue;\n        }\n        if (String(json?.status || '').toLowerCase() === 'fail') {\n            throw new CommandExecutionError('Instagram private publish configure_sidecar failed', message || text.slice(0, 500));\n        }\n        return { code: json?.media?.code };","sourceCodeStart":836,"sourceCodeEnd":872,"githubUrl":"https://github.com/jackwener/OpenCLI/blob/49907e53dc3ade5c223ff0c4c2c2785687cec4e6/clis/instagram/_shared/private-publish.js#L836-L872","documentation":"publishSidecarWithRetry POSTs to https://www.instagram.com/api/v1/media/configure_sidecar/ and JSON.parses the raw response body. When the body is non-empty but not valid JSON (HTML login page, rate-limit page, proxy interstitial, garbage body), the parse throws and the library converts it into this CommandExecutionError instead of leaking a raw SyntaxError.","triggerScenarios":"The configure_sidecar HTTP response has a non-empty body that fails JSON.parse — e.g. Instagram returned an HTML login/challenge page, a Cloudflare/proxy block page, or truncated/garbage text instead of the expected JSON envelope.","commonSituations":"Expired or invalid session cookies so the private API returns the login HTML page; datacenter IP blocked by Instagram returning a challenge page; corporate proxy injecting HTML; transient 5xx returning an HTML error page.","solutions":["Inspect the raw response via fetch interception/debug logging on the configure_sidecar call to see the actual body.","Refresh the Instagram session cookies / re-login; a stale session is the most common cause of HTML responses.","Retry after a delay; transient Instagram 5xx or rate-limiting often returns non-JSON bodies.","Check the network path (proxy/VPN) is not injecting HTML into API responses.","Verify the request headers built by buildPrivateApiHeaders are correct (missing headers can trigger challenge pages)."],"exampleFix":"// before\nconst text = await response.text();\n// after\nconst text = await response.text();\nif (/^\\s*</.test(text)) throw new Error('configure_sidecar returned HTML (session expired?): ' + text.slice(0, 200));","handlingStrategy":"try-catch","validationCode":"// Sanity-check session before private publish\nconst cookies = await page.context().cookies('https://www.instagram.com');\nif (!cookies.some(c => c.name === 'ds_user_id')) throw new Error('Not logged in — configure_sidecar would return HTML');","typeGuard":"function isJsonObject(value) {\n  return typeof value === 'object' && value !== null && !Array.isArray(value);\n}","tryCatchPattern":"try {\n  await publishMediaViaPrivateApi({ mediaItems, apiContext });\n} catch (e) {\n  if (/returned invalid JSON/.test(e.message)) {\n    await refreshInstagramSession(page); // HTML body usually means dead session\n    await publishMediaViaPrivateApi({ mediaItems, apiContext });\n  } else throw e;\n}","preventionTips":["Verify session cookies (ds_user_id, csrftoken) exist before private API calls.","Publish from residential IPs to avoid challenge pages.","Log raw response bodies on failure for diagnosis.","Back off and retry on transient Instagram 5xx."],"tags":["instagram","json-parse","http-response","private-api"],"backgroundTag":"invalid-json-response","analyzedSha":"49907e53dc3ade5c223ff0c4c2c2785687cec4e6","analyzedAt":"2026-08-29T08:14:47.543Z","schemaVersion":2},"datasetVersion":"2026-08-29T12:17:43.993Z"}