Registry / communication / instagram-private-api

instagram-private-api

JSON →
library1.6.0.0jsnpmunverified

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.

npm install instagram-private-api
INSTALL
IMPORT
SIG · INSTAGRAM-PRIVATE-
I
instagram-private-api
communicationjavascriptv1.6.0.0
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

IgApiClient
import { IgApiClient } from 'instagram-private-api';
const { IgApiClient } = require('instagram-private-api');
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.
IgCheckpointError
import { IgCheckpointError } from 'instagram-private-api';
import IgCheckpointError from 'instagram-private-api';
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.
IgLoginTwoFactorRequiredError
import { IgLoginTwoFactorRequiredError } from 'instagram-private-api';
import IgLoginTwoFactorRequiredError from 'instagram-private-api';
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.

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.

import { IgApiClient } from 'instagram-private-api'; import { writeFile, readFile } from 'node:fs/promises'; import path from 'node:path'; const ig = new IgApiClient(); const stateFilePath = path.join(process.cwd(), 'ig_state.json'); // Generate device IDs based on a seed (e.g., username) for consistent behavior ig.state.generateDevice(process.env.IG_USERNAME ?? ''); // Optionally, set a proxy URL ig.state.proxyUrl = process.env.IG_PROXY ?? ''; // Attempt to load previously saved state (like cookies, device IDs) // This is crucial for avoiding frequent Instagram challenges. async function loadState() { try { ig.state.deserialize(await readFile(stateFilePath, { encoding: 'utf8' })); console.log('Successfully restored Instagram state.'); } catch (e) { console.log('No saved state found or error loading state, starting fresh.'); } } // Save the current state after successful login or important operations async function saveState() { await writeFile(stateFilePath, await ig.state.serialize(), { encoding: 'utf8' }); console.log('Instagram state saved.'); } (async () => { if (!process.env.IG_USERNAME || !process.env.IG_PASSWORD) { console.error('Please set IG_USERNAME and IG_PASSWORD environment variables.'); process.exit(1); } await loadState(); // Try to load state before logging in // Execute pre-login flow to mimic a real Android application await ig.simulate.preLoginFlow(); const loggedInUser = await ig.account.login(process.env.IG_USERNAME, process.env.IG_PASSWORD); console.log(`Logged in as ${loggedInUser.username} (${loggedInUser.pk})`); await saveState(); // Save state after successful login // Example: Get user feed (your own) const myFeed = ig.feed.user(loggedInUser.pk); const myItems = await myFeed.items(); console.log('First 3 items from your feed:', myItems.slice(0, 3).map(item => item.id)); // Example: Fetch a public user's profile info const targetUsername = 'instagram'; // Or any public account const targetUser = await ig.user.searchExact(targetUsername); console.log(`Info for ${targetUser.username}: followers=${targetUser.follower_count}, following=${targetUser.following_count}`); // Log out (optional, but good practice) // await ig.account.logout(); // console.log('Logged out.'); })();
Debug
Known issues
breakingFuture 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.
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.
affects: >=1.0.0
breakingThe 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.
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.
affects: >=1.0.0
gotchaFailing 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`.
fix
Explicitly install `re2` alongside `instagram-private-api` by running `npm install re2`. This is critical for security and stability.
affects: >=1.0.0
gotchaFor 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.
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.
affects: <13.5.0
gotchaInstagram 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.
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.
affects: >=1.0.0
Errors
Common errors & fixes
Cannot use import statement outside a module
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`).
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.
Error: Challenge required.
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.
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.
Error: login: Please wait a few minutes before you try again.
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.
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.
Error: User '...' not found.
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.
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).
Upgrade
Version history
1.6.0.0latest on npm
Audit
Dependencies
re2optionalPeer 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.
Agent activity
22 hits · last 30 days
node
20
OpenAI (training)
1
Resources
instagram-private-api — npm install instagram-private-api · libregistry