{"id":13338,"library":"instagram-private-api","title":"Instagram Private API Client","description":"instagram-private-api is a Node.js wrapper for the unofficial Instagram private API, providing programmatic access to various Instagram functionalities typically found in the official mobile applications. The current stable public version is 1.46.1. While it offers extensive features for interacting with Instagram, development for future major versions (e.g., v3.x.x) has transitioned to a private, paid monorepository, shifting active feature development away from this public npm package. This means the public package is primarily in a maintenance state, receiving minimal updates for new features. Key differentiators include its ability to mimic actual device behavior and handle session state, crucial for managing unofficial API interactions.","status":"maintenance","version":"1.46.1","language":"javascript","source_language":"en","source_url":"https://github.com/dilame/instagram-private-api","tags":["javascript","typescript"],"install":[{"cmd":"npm install instagram-private-api","lang":"bash","label":"npm"},{"cmd":"yarn add instagram-private-api","lang":"bash","label":"yarn"},{"cmd":"pnpm add instagram-private-api","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Peer dependency strongly recommended to mitigate a Regular Expression Denial of Service (ReDoS) vulnerability (CVE-2020-7661) related to the internal `url-regex-safe` dependency when sending direct messages.","package":"re2","optional":true}],"imports":[{"note":"Use named import for the main client class when working in an ES module environment (Node.js 13.5.0+ or `\"type\": \"module\"`). CommonJS `require` syntax is necessary for older Node.js versions or CJS modules.","wrong":"const { IgApiClient } = require('instagram-private-api');","symbol":"IgApiClient","correct":"import { IgApiClient } from 'instagram-private-api';"},{"note":"This named export is used for catching errors when Instagram requires a checkpoint verification (e.g., phone/email code) during login or sensitive actions. Do not attempt a default import.","wrong":"import IgCheckpointError from 'instagram-private-api';","symbol":"IgCheckpointError","correct":"import { IgCheckpointError } from 'instagram-private-api';"},{"note":"This named export is thrown when an account has two-factor authentication enabled and requires a verification code during login. Handle this error to implement 2FA resolution.","wrong":"import IgLoginTwoFactorRequiredError from 'instagram-private-api';","symbol":"IgLoginTwoFactorRequiredError","correct":"import { IgLoginTwoFactorRequiredError } from 'instagram-private-api';"}],"quickstart":{"code":"import { IgApiClient } from 'instagram-private-api';\nimport { writeFile, readFile } from 'node:fs/promises';\nimport path from 'node:path';\n\nconst ig = new IgApiClient();\nconst stateFilePath = path.join(process.cwd(), 'ig_state.json');\n\n// Generate device IDs based on a seed (e.g., username) for consistent behavior\nig.state.generateDevice(process.env.IG_USERNAME ?? '');\n\n// Optionally, set a proxy URL\nig.state.proxyUrl = process.env.IG_PROXY ?? '';\n\n// Attempt to load previously saved state (like cookies, device IDs)\n// This is crucial for avoiding frequent Instagram challenges.\nasync function loadState() {\n  try {\n    ig.state.deserialize(await readFile(stateFilePath, { encoding: 'utf8' }));\n    console.log('Successfully restored Instagram state.');\n  } catch (e) {\n    console.log('No saved state found or error loading state, starting fresh.');\n  }\n}\n\n// Save the current state after successful login or important operations\nasync function saveState() {\n  await writeFile(stateFilePath, await ig.state.serialize(), { encoding: 'utf8' });\n  console.log('Instagram state saved.');\n}\n\n(async () => {\n  if (!process.env.IG_USERNAME || !process.env.IG_PASSWORD) {\n    console.error('Please set IG_USERNAME and IG_PASSWORD environment variables.');\n    process.exit(1);\n  }\n\n  await loadState(); // Try to load state before logging in\n\n  // Execute pre-login flow to mimic a real Android application\n  await ig.simulate.preLoginFlow();\n\n  const loggedInUser = await ig.account.login(process.env.IG_USERNAME, process.env.IG_PASSWORD);\n  console.log(`Logged in as ${loggedInUser.username} (${loggedInUser.pk})`);\n\n  await saveState(); // Save state after successful login\n\n  // Example: Get user feed (your own)\n  const myFeed = ig.feed.user(loggedInUser.pk);\n  const myItems = await myFeed.items();\n  console.log('First 3 items from your feed:', myItems.slice(0, 3).map(item => item.id));\n\n  // Example: Fetch a public user's profile info\n  const targetUsername = 'instagram'; // Or any public account\n  const targetUser = await ig.user.searchExact(targetUsername);\n  console.log(`Info for ${targetUser.username}: followers=${targetUser.follower_count}, following=${targetUser.following_count}`);\n\n  // Log out (optional, but good practice)\n  // await ig.account.logout();\n  // console.log('Logged out.');\n})();","lang":"typescript","description":"This quickstart demonstrates how to initialize the Instagram API client, log in using environment variables, handle crucial session state persistence (saving/loading cookies and device info to a file), and fetch basic user data from your own and a public profile."},"warnings":[{"fix":"Users requiring new features or active development beyond critical fixes for v1.x will need to contact the maintainer for access to the private repository, or consider alternative solutions.","message":"Future major versions (e.g., 3.x.x) of this library have moved to a private, paid repository. The public `instagram-private-api` npm package is now in a maintenance-only state, meaning new features and significant updates will not be publicly released.","severity":"breaking","affected_versions":">=1.0.0"},{"fix":"Implement robust error handling, use proxies, rotate user-agents, and manage session state carefully. Be prepared for frequent updates or changes to your implementation if Instagram alters its internal API. Always use a dedicated test account for development and avoid using personal accounts for automation.","message":"The library interacts with an unofficial Instagram API and is highly sensitive to Instagram's evolving anti-bot measures. Frequent changes on Instagram's side can cause the API to break or accounts to be challenged/banned without warning. This is an inherent risk of using any unofficial private API.","severity":"breaking","affected_versions":">=1.0.0"},{"fix":"Explicitly install `re2` alongside `instagram-private-api` by running `npm install re2`. This is critical for security and stability.","message":"Failing to install the `re2` peer dependency can lead to a Regular Expression Denial of Service (ReDoS) vulnerability (CVE-2020-7661) when sending direct messages due to the internal use of `url-regex-safe`.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Use CommonJS `require` syntax: `const { IgApiClient } = require('instagram-private-api');`. Alternatively, configure your project for transpilation (e.g., with Babel or TypeScript targeting CommonJS) or ensure your `package.json` specifies `\"type\": \"module\"` for ES module support on newer Node.js versions.","message":"For Node.js versions older than 13.5.0, or when your project is configured as CommonJS, ES module `import` syntax is not natively supported. Attempting to use `import` directly will result in syntax errors.","severity":"gotcha","affected_versions":"<13.5.0"},{"fix":"Always call `ig.state.generateDevice(process.env.IG_USERNAME ?? '');` with a consistent seed and `await ig.simulate.preLoginFlow();` before logging in. Implement robust session state persistence by serializing and deserializing `ig.state` to disk. You may need to catch `IgCheckpointError` and `IgLoginTwoFactorRequiredError` to implement custom challenge resolution logic.","message":"Instagram often triggers security challenges (e.g., phone/email verification, checkpoint) if the login flow or device state is not handled correctly, especially for new accounts, new IP addresses, or inconsistent session data.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Change your import statements to CommonJS `require`: `const { IgApiClient } = require('instagram-private-api');`. If using TypeScript, ensure your `tsconfig.json`'s `module` option is set to `CommonJS` or correctly configured for ESNext output with appropriate runtime support.","cause":"Attempting to use ES module `import` syntax in a Node.js environment that does not natively support it (e.g., older Node.js versions, or a `.js` file without `\"type\": \"module\"` in `package.json`).","error":"Cannot use import statement outside a module"},{"fix":"Ensure `ig.state.generateDevice()` is called with a consistent seed and `ig.simulate.preLoginFlow()` is run before login. Crucially, implement session state persistence by saving and loading `ig.state.serialize()` to avoid repeated challenges. You will likely need to catch `IgCheckpointError` and implement a challenge resolver workflow.","cause":"Instagram has flagged the login attempt or a subsequent action as suspicious, requiring a security challenge (e.g., email/phone verification, CAPTCHA). This often happens with new accounts, new IPs, or inconsistent device states.","error":"Error: Challenge required."},{"fix":"Wait for a period (e.g., 10-30 minutes, sometimes longer) before retrying. Consider using proxies (`ig.state.proxyUrl`) and rotating them. Avoid rapid, repetitive actions immediately after login. Ensure `generateDevice` and `preLoginFlow` are correctly used, and ensure login credentials are accurate.","cause":"Too many login attempts, rapid API calls, or rate-limiting by Instagram due to detected suspicious activity from your IP address or account. This can also occur if login details are incorrect repeatedly.","error":"Error: login: Please wait a few minutes before you try again."},{"fix":"Double-check the username for correctness. Verify that the account is public (if attempting public searches) or that the credentials are for a valid, active account (if attempting login).","cause":"The Instagram username provided for login or search does not exist, is misspelled, or the account might be private/disabled/deleted and inaccessible via direct search.","error":"Error: User '...' not found."}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":null,"cli_name":"","cli_version":null}