npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

instagram-graph-api-sdk

v1.0.0

Published

Type-safe TypeScript SDK for Instagram Graph API with Instagram Login

Readme

Instagram Graph API SDK

Type-safe TypeScript SDK for Instagram Graph API with Instagram Login.

Installation

npm install instagram-graph-api-sdk

Quick Start

import { InstagramClient } from 'instagram-graph-api-sdk';

const client = new InstagramClient({
  accessToken: 'your-access-token',
  apiVersion: 'v22.0', // optional, defaults to v22.0
});

// Get user profile
const profile = await client.users.getProfile({
  fields: ['id', 'username', 'followers_count'],
});
console.log(profile);

Features

  • 🔒 Type-safe: Full TypeScript support with comprehensive type definitions
  • 📦 Class-based: Clean, intuitive API with organized modules
  • 🔧 Maintainable: Centralized endpoint definitions for easy updates
  • Modern: ESM and CommonJS support, async/await throughout

API Modules

| Module | Description | |--------|-------------| | InstagramOAuth | OAuth flow (static methods, no token needed) | | client.auth | Token management and user info | | client.users | Profile, media, stories, insights | | client.media | Get media, children, comments | | client.publishing | Publish images, videos, reels, stories, carousels | | client.messaging | Send messages, templates, quick replies | | client.conversations | List conversations, get messages | | client.comments | Comment moderation (hide, delete, reply) | | client.hashtags | Search hashtags, get media | | client.insights | Account and media analytics | | client.welcomeFlows | Welcome message flows | | client.messengerProfile | Ice breakers, persistent menu | | client.oembed | Embed Instagram content |

OAuth Flow (Instagram Business Login)

The SDK handles the complete OAuth flow for Instagram Business Login.

Step 1: Build Authorization URL

import { InstagramOAuth } from 'instagram-graph-api-sdk';

// Build the URL to redirect users to
const authUrl = InstagramOAuth.buildAuthorizationUrl({
  clientId: process.env.INSTAGRAM_APP_ID!,
  redirectUri: `${process.env.APP_URL}/api/instagram/callback`,
  scopes: [
    'instagram_business_basic',
    'instagram_business_manage_messages',
    'instagram_business_manage_comments',
    'instagram_business_content_publish',
  ],
  state: crypto.randomUUID(), // CSRF protection
});

// Redirect user to authUrl

Step 2: Handle Callback & Exchange Token

import { InstagramOAuth, InstagramClient } from 'instagram-graph-api-sdk';

// In your callback handler
const { code, state, error } = InstagramOAuth.parseCallback(request.url);

if (error) {
  // User denied access
  console.log('OAuth error:', error);
  return;
}

// Exchange code for long-lived token (60 days)
const tokens = await InstagramOAuth.exchangeCodeForToken({
  clientId: process.env.INSTAGRAM_APP_ID!,
  clientSecret: process.env.INSTAGRAM_APP_SECRET!,
  code: code!,
  redirectUri: `${process.env.APP_URL}/api/instagram/callback`,
});

// Store in your database
await db.instagramAccount.create({
  userId: currentUser.id,
  accessToken: tokens.access_token,
  igUserId: tokens.user_id,
  expiresAt: new Date(Date.now() + tokens.expires_in * 1000),
});

Step 3: Use the Client

// Create client with stored token
const client = new InstagramClient({
  accessToken: storedAccount.accessToken,
});

// Make API calls
const profile = await client.users.getProfile();
await client.publishing.createImageContainer({...});

Multi-User Support

The SDK is designed for multi-user apps. Each user has their own token:

async function getClientForUser(userId: string) {
  const account = await db.instagramAccount.findUnique({ where: { userId } });
  return new InstagramClient({ accessToken: account.accessToken });
}

// Use for specific user
const client = await getClientForUser(userId);
const media = await client.users.getMedia();

Usage Examples

Get User Media

const media = await client.users.getMedia({
  limit: 10,
  fields: ['id', 'caption', 'media_type', 'permalink'],
});

for (const item of media.data) {
  console.log(item.permalink);
}

Publish a Reel

// Create video container
const container = await client.publishing.createVideoContainer({
  video_url: 'https://example.com/video.mp4',
  media_type: 'REELS',
  caption: 'Check out this reel! 🎬',
});

// Wait for processing and publish
const result = await client.publishing.waitAndPublish(container.id);
console.log('Published:', result.id);

Send a Message

// Send text message
await client.messaging.sendText(recipientId, 'Hello from the SDK!');

// Send image
await client.messaging.sendMedia(recipientId, {
  type: 'image',
  url: 'https://example.com/image.jpg',
});

// Send quick replies
await client.messaging.sendQuickReplies(recipientId, {
  text: 'What would you like to do?',
  replies: [
    { content_type: 'text', title: 'View Products', payload: 'VIEW_PRODUCTS' },
    { content_type: 'text', title: 'Contact Us', payload: 'CONTACT' },
  ],
});

Comment Moderation

// Get comments on media
const comments = await client.media.getComments(mediaId, { limit: 20 });

// Hide a spam comment
await client.comments.hide(commentId);

// Reply to a comment
await client.comments.reply(commentId, { message: 'Thanks for your comment!' });

// Send private reply to comment
await client.messaging.sendPrivateReply(commentId, 'Hi, let me help you!');

Ice Breakers

// Set ice breaker questions
await client.messengerProfile.setIceBreakers([
  {
    call_to_actions: [
      { question: 'What are your hours?', payload: 'HOURS' },
      { question: 'Where are you located?', payload: 'LOCATION' },
      { question: 'How can I order?', payload: 'ORDER' },
    ],
  },
]);

Get Insights

// Account insights
const insights = await client.insights.getAccountInsights({
  metric: ['impressions', 'reach', 'profile_views'],
  period: 'day',
});

// Media insights
const mediaInsights = await client.insights.getMediaInsights(mediaId, {
  metric: ['engagement', 'impressions', 'reach'],
});

Error Handling

import {
  InstagramAPIError,
  AuthenticationError,
  RateLimitError,
  isRateLimitError,
} from 'instagram-graph-api-sdk';

try {
  const profile = await client.users.getProfile();
} catch (error) {
  if (isRateLimitError(error)) {
    console.log('Rate limited, retry after:', error.retryAfter);
  } else if (error instanceof AuthenticationError) {
    console.log('Token expired, refresh needed');
  } else if (error instanceof InstagramAPIError) {
    console.log('API error:', error.message, error.code);
  }
}

Configuration

const client = new InstagramClient({
  accessToken: 'your-access-token',
  apiVersion: 'v22.0',  // API version (default: v22.0)
  timeout: 30000,       // Request timeout in ms (default: 30000)
});

// Update token later
client.setAccessToken('new-access-token');

Requirements

  • Node.js 18+
  • Instagram Professional Account (Business or Creator)
  • Instagram Business Login configured

License

Licensed under the Apache License 2.0. See the LICENSE file for details.