Socket
Book a DemoInstallSign in
Socket

nodejs-insta-private-api

Package Overview
Dependencies
Maintainers
1
Versions
42
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

nodejs-insta-private-api

A pure JavaScript Instagram Private API client inspired by instagram-private-api

Source
npmnpm
Version
4.9.0
Version published
Weekly downloads
1.1K
1497.06%
Maintainers
1
Weekly downloads
 
Created
Source

nod ejs-insta-private-api

Version 3.3.1 — Updated for the latest Instagram version

A pure JavaScript Instagram Private API client written in CommonJS (no TypeScript).

Repository: Kunboruto20/nodejs-insta-private-api

Features

Authentication — Username, email, and password login with session management

Direct Messages — Send text, images, and videos to users and groups

Stories — React to stories, upload content, and view story feeds

Feed Operations — Upload photos/videos, like, comment, and browse timeline

Session Management — Save and restore login sessions

Auto-retry — Built-in retry logic for failed requests

Comprehensive API — 50+ methods covering most Instagram features

High Performance — Optimized for speed and reliability

Realtime MQTT — Real-time events via MQTT using edge-mqtt.facebook.com (GraphQL, Pub/Sub, Message Sync, Iris)

Installation

npm install nodejs-insta-private-api

Quick Start

Basic Usage

const { IgApiClient } = require('nodejs-insta-private-api');

async function main() {
const ig = new IgApiClient();

try {
await ig.login({
username: 'your_username',
password: 'your_password',
email: 'your_email@example.com'
});

console.log('Logged in successfully!');  
  
await ig.dm.send({   
  to: 'friend_username',   
  message: 'Hello from the API!'   
});  
  
console.log('Message sent!');  
  

} catch (error) {
console.error('Error:', error.message);
}
}

main();

Extending with instagram_mqttt for Realtime and FBNS

This library can be extended with instagram_mqttt to add Realtime and FBNS (Push Notifications) support.

Install instagram_mqttt

npm install instagram_mqttt

Extend the IgApiClient

import { IgApiClient } from 'nodejs-insta-private-api';
import { withFbnsAndRealtime, withFbns, withRealtime } from 'instagram_mqttt';

// Wrap the client
// ig is now IgApiClientMQTT for TypeScript users
const ig = withFbnsAndRealtime(new IgApiClient());

// OR if you only want fbns/realtime
const igFbns = withFbns(new IgApiClient());
const igRealtime = withRealtime(new IgApiClient());

// Login normally or load session

// Use ig.realtime and ig.fbns

RealtimeClient Features

Typing events

Presence events

Direct messaging

Live comments

Live events

FbnsClient Usage

FBNS is for notifications (read-only). You can subscribe to any notification:

ig.fbns.on('push', (data) => {
console.log('Push notification:', data);
});

Or subscribe to a specific event:

ig.fbns.on('collapseKey', (data) => {
console.log('Specific notification:', data);
});

Table of Contents

Authentication

Direct Messages

Stories

Feed Operations

User Operations

Media Operations

Session Management

Error Handling

Advanced Usage

API Reference

Requirements

Dependencies

Contributing

License

Disclaimer

Support

Changelog

Authentication

Basic Login

const { IgApiClient } = require('nodejs-insta-private-api');
const ig = new IgApiClient();

// Login with username and password
await ig.login({
username: 'your_username',
password: 'your_password',
email: 'your_email@example.com' // Optional but recommended
});

// Check if logged in
if (ig.isLoggedIn()) {
console.log('Successfully logged in!');
}

Two-Factor Authentication

try {
await ig.login({ username, password, email });
} catch (error) {
if (error.name === 'IgLoginTwoFactorRequiredError') {
const code = '123456'; // Get from user input
await ig.account.twoFactorLogin({
username,
verificationCode: code,
twoFactorIdentifier: error.response.data.two_factor_info.two_factor_identifier
});
}
}

Session Management

const fs = require('fs');

// Save session after login
const session = await ig.saveSession();
fs.writeFileSync('session.json', JSON.stringify(session));

// Load session later
const loaded = JSON.parse(fs.readFileSync('session.json'));
await ig.loadSession(loaded);

// Check if session is still valid
if (await ig.isSessionValid()) {
console.log('Session is valid!');
} else {
console.log('Need to login again');
}

Direct Messages

Send Text Messages

// Send to a single user
await ig.dm.send({
to: 'username',
message: 'Hello!'
});

// Send to multiple users
await ig.dm.send({
to: ['user1', 'user2', 'user3'],
message: 'Group message!'
});

Send to Groups

// Send to existing group by thread ID
await ig.dm.sendToGroup({
threadId: 'group_thread_id',
message: 'Hello group!'
});

// Create new group and send message
const group = await ig.direct.createGroupThread(
['user1', 'user2', 'user3'],
'My Group Name'
);

await ig.dm.sendToGroup({
threadId: group.thread_id,
message: 'Welcome to the group!'
});

Send Media

// Send image
await ig.dm.sendImage({
to: 'username',
imagePath: './photo.jpg'
});

// Send video
await ig.dm.sendVideo({
to: 'username',
videoPath: './video.mp4'
});

Manage Inbox

// Get inbox
const inbox = await ig.dm.getInbox();
console.log(You have ${inbox.inbox.threads.length} conversations);

// Get specific thread
const thread = await ig.dm.getThread('thread_id');

// Mark messages as seen
for (const item of thread.thread.items) {
await ig.directThread.markItemSeen(thread.thread.thread_id, item.item_id);
}

Stories

React to Stories

await ig.story.react({
storyId: 'story_media_id',
reaction: '❤️'
});

await ig.story.react({
storyId: 'story_media_id',
reaction: '🔥'
});

View Stories

const storyFeed = await ig.story.getFeed();
const userStories = await ig.story.getUser('user_id');
await ig.story.seen(userStories.reel.items);

Upload Stories

await ig.story.upload({
imagePath: './story.jpg',
caption: 'My story! #instagram'
});

await ig.story.uploadVideo({
videoPath: './story.mp4',
caption: 'Video story!',
duration_ms: 15000
});

Story Highlights

const highlights = await ig.story.getHighlights('user_id');
const highlight = await ig.story.getHighlight('highlight_id');

Feed Operations

Upload Posts

await ig.feed.upload({
imagePath: './photo.jpg',
caption: 'My awesome photo! #photography #instagram'
});

await ig.feed.uploadVideo({
videoPath: './video.mp4',
caption: 'Check out this video!',
duration_ms: 30000,
width: 720,
height: 1280
});

Upload Carousel (Multiple Photos/Videos)

await ig.feed.uploadCarousel({
items: [
{ type: 'photo', path: './photo1.jpg' },
{ type: 'photo', path: './photo2.jpg' },
{ type: 'video', path: './video1.mp4', duration_ms: 15000 }
],
caption: 'My carousel post! Swipe to see more.'
});

Browse Feeds

const timeline = await ig.feed.getFeed();
const userFeed = await ig.feed.getUserFeed('user_id');
const hashtagFeed = await ig.feed.getTag('photography');
const locationFeed = await ig.feed.getLocation('location_id');
const exploreFeed = await ig.feed.getExploreFeed();
const likedPosts = await ig.feed.getLiked();
const savedPosts = await ig.feed.getSaved();

User Operations

User Information

const userByName = await ig.user.infoByUsername('instagram');
const userById = await ig.user.info('user_id');
const users = await ig.user.search('john');

Follow/Unfollow

await ig.user.follow('user_id');
await ig.user.unfollow('user_id');
const followers = await ig.user.getFollowers('user_id');
const following = await ig.user.getFollowing('user_id');

Media Operations

Interact with Posts

await ig.media.like('media_id');
await ig.media.unlike('media_id');
await ig.media.comment('media_id', 'Great post!');
const mediaInfo = await ig.media.info('media_id');
const likers = await ig.media.likers('media_id');
const comments = await ig.media.comments('media_id');

Manage Your Posts

await ig.media.edit('media_id', 'New caption text');
await ig.media.delete('media_id');
await ig.media.deleteComment('media_id', 'comment_id');

Error Handling

Basic Error Handling

const { IgApiClient } = require('nodejs-insta-private-api');
const Utils = require('nodejs-insta-private-api/dist/utils');

try {
await ig.login({ username, password, email });
} catch (error) {
console.log('Error type:', error.name);
console.log('Human readable:', Utils.humanizeError(error));

switch (error.name) {
case 'IgLoginBadPasswordError':
console.log('Wrong password!');
break;
case 'IgLoginTwoFactorRequiredError':
console.log('2FA required');
break;
case 'IgCheckpointError':
console.log('Account verification required');
break;
case 'IgActionSpamError':
console.log('Action blocked - wait before retrying');
break;
default:
console.log('Unknown error:', error.message);
}
}

Retry Logic

const Utils = require('nodejs-insta-private-api/dist/utils');

await Utils.retryOperation(async () => {
return await ig.dm.send({ to: 'username', message: 'Hello!' });
}, 3, 2000); // 3 retries, 2 second delay

Advanced Usage

Rate Limiting

const Utils = require('nodejs-insta-private-api/dist/utils');

await ig.dm.send({ to: 'user1', message: 'Hello!' });
await Utils.randomDelay(1000, 3000);
await ig.dm.send({ to: 'user2', message: 'Hello!' });

Batch Operations

const users = ['user1', 'user2', 'user3'];
const message = 'Hello from the API!';

for (const user of users) {
try {
await ig.dm.send({ to: user, message });
console.log(Message sent to ${user});
await Utils.randomDelay(2000, 5000);
} catch (error) {
console.log(Failed to send to ${user}:, error.message);
}
}

File Validation

const Utils = require('nodejs-insta-private-api/dist/utils');

if (Utils.isImageFile('./photo.jpg') && Utils.validateFileSize('./photo.jpg', 8 * 1024 * 1024)) {
await ig.feed.upload({
imagePath: './photo.jpg',
caption: 'Valid image!'
});
} else {
console.log('Invalid file!');
}

API Reference

IgApiClient

Main client class for interacting with Instagram.

const ig = new IgApiClient();

Methods

login(credentials) - Login with username/password

logout() - Logout and clear session

isLoggedIn() - Check if currently logged in

saveSession() - Save current session

loadSession(session) - Load saved session

isSessionValid() - Check if session is valid

destroy() - Cleanup resources

Realtime Methods

connectRealtime() - Connect to MQTT broker

disconnectRealtime() - Disconnect from MQTT broker

isRealtimeConnected() - Check connection status

pingRealtime() - Send ping to broker

getRealtimeStats() - Get connection statistics

setRealtimeReconnectOptions(options) - Configure reconnection behavior

Repositories

All repositories are accessible through the main client:

ig.account - Account operations

ig.user - User operations

ig.direct - Direct message operations

ig.directThread - Thread management

ig.media - Media operations

ig.upload - File uploads

ig.story - Story operations

ig.feed - Feed operations

Convenient Access

ig.dm - Shortcut for common DM operations

send(options) - Send message

sendToGroup(options) - Send to group

sendImage(options) - Send image

sendVideo(options) - Send video

getInbox() - Get inbox

getThread(id) - Get thread

Requirements

Node.js >= 14.0.0

Valid Instagram account

Dependencies

axios — HTTP client

tough-cookie — Cookie management

form-data — Form data handling

chance — Random data generation

lodash — Utility functions

Contributing

Repository: Kunboruto20/nodejs-insta-private-api

  • Fork the repository

  • Create your feature branch (git checkout -b feature/amazing-feature)

  • Commit your changes (git commit -m 'Add some amazing feature')

  • Push to the branch (git push origin feature/amazing-feature)

  • Open a Pull Request

Keywords

instagram

FAQs

Package last updated on 12 Nov 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts