{"record":{"id":"6def504ce022e401","repo":"jackwener/OpenCLI","slug":"instagram-follow-returned-invalid-json","errorCode":null,"errorMessage":"Instagram follow returned invalid JSON","messagePattern":"Instagram follow returned invalid JSON","errorType":"exception","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"clis/instagram/follow.js","lineNumber":38,"sourceCode":"        { evaluate: `(async () => {\n  const username = \\${{ args.username | json }};\n  const headers = { 'X-IG-App-ID': '936619743392459' };\n  const opts = { credentials: 'include', headers };\n\n  ${buildResolveInstagramUserIdJs()}\n\n  const csrf = document.cookie.match(/csrftoken=([^;]+)/)?.[1] || '';\n  const r2 = await fetch('https://www.instagram.com/api/v1/friendships/create/' + userId + '/', {\n    method: 'POST',\n    credentials: 'include',\n    headers: { ...headers, 'X-CSRFToken': csrf, 'Content-Type': 'application/x-www-form-urlencoded' },\n  });\n  if (!r2.ok) throw new Error('Failed to follow: HTTP ' + r2.status);\n  let d2;\n  try {\n    d2 = await r2.json();\n  } catch {\n    throw new Error('Instagram follow returned invalid JSON');\n  }\n  if (!d2 || typeof d2 !== 'object' || d2.status !== 'ok' || !d2.friendship_status || typeof d2.friendship_status !== 'object') {\n    throw new Error('Instagram follow returned no success evidence');\n  }\n  const status = d2.friendship_status.following ? 'Following' : d2.friendship_status.outgoing_request ? 'Request sent' : '';\n  if (!status) throw new Error('Instagram follow returned no success evidence');\n  return [{ status, username }];\n})()\n` },\n    ],\n});\n","sourceCodeStart":20,"sourceCodeEnd":50,"githubUrl":"https://github.com/jackwener/OpenCLI/blob/49907e53dc3ade5c223ff0c4c2c2785687cec4e6/clis/instagram/follow.js#L20-L50","documentation":"This CLI's follow command issues a POST to Instagram's private web API endpoint /api/v1/friendships/create/<userId>/ from within the browser session. After the fetch resolves with a 2xx response, it calls r2.json(); if the body cannot be parsed as JSON (HTML error page, empty body, CSP/blocked response), the parse throws and this error is raised instead. It means Instagram answered HTTP-ok but not with a JSON friendship payload.","triggerScenarios":"The POST to /api/v1/friendships/create/ returns 2xx with a non-JSON body: an HTML login/challenge interstitial, an empty 204-style body, a Cloudflare/anti-bot challenge page, or a response intercepted/modified by an extension.","commonSituations":"Session cookies expired so Instagram serves an HTML redirect page with 200; logged-out or soft-banned account; Instagram A/B serving different content; corporate proxy or extension rewriting responses; rate-limit soft responses rendered as HTML.","solutions":["Re-authenticate in the browser (log into instagram.com) so the POST returns the real JSON friendship payload instead of an HTML page.","Retry the follow command; transient anti-bot challenges often clear on a fresh navigation.","Check network tab / response body for the actual content to confirm whether it's a login redirect or challenge page.","If persistent, verify the account isn't action-blocked (temporary follow restrictions) which can cause non-JSON soft responses."],"exampleFix":"// before (caller assumes JSON always present)\nconst d2 = await r2.json();\n// after (mirror library's guard)\nlet d2;\ntry { d2 = await r2.json(); }\ncatch { throw new Error('Instagram follow returned invalid JSON'); }","handlingStrategy":"try-catch","validationCode":"// Nothing to validate pre-call (server-side body), but ensure an authenticated session exists:\nconst loggedIn = document.cookie.includes('ds_user_id');\nif (!loggedIn) throw new Error('Not logged into Instagram; follow would return non-JSON');","typeGuard":"function isJsonObject(v) { return v !== null && typeof v === 'object' && !Array.isArray(v); }\n// usage: if (!isJsonObject(d2)) { /* treat as invalid JSON payload */ }","tryCatchPattern":"try {\n  const res = await followUser(username);\n} catch (e) {\n  if (String(e.message).includes('invalid JSON')) {\n    // re-login / refresh session, then retry once\n  } else throw e;\n}","preventionTips":["Always operate from a logged-in browser session with fresh cookies.","Check r.ok AND content-type: application/json before calling r.json().","Log the raw response text on parse failure to diagnose HTML vs empty bodies.","Avoid running during known anti-bot challenge windows; throttle writes."],"tags":["instagram","network","json-parsing","browser-automation"],"backgroundTag":"invalid-json-response","analyzedSha":"49907e53dc3ade5c223ff0c4c2c2785687cec4e6","analyzedAt":"2026-08-29T08:14:47.543Z","schemaVersion":2},"datasetVersion":"2026-08-29T12:17:43.993Z"}