Social Media Scraper

Tutorials

Scrape Instagram Comments with JavaScript

Collect public Instagram post and Reel comments into clean JSON from Node.js 18+ using native fetch—no Playwright browser automation, no Instagram session cookies, and zero third-party npm packages. Run the script strictly on the server with SOCIALSCRAPER_API_KEY in environment variables so credentials never reach client-side JavaScript.

  • Zero npm dependencies — uses Node.js 18+ built-in fetch, node:fs/promises, node:crypto, and AbortSignal.timeout(45000).
  • Structured comments.json output — saves {source_url, items, cursor} straight from GET /v1/instagram/comments.
  • Safe fail-fast execution — generates a fresh randomUUID() Idempotency-Key per call and exits cleanly on non-2xx HTTP statuses.
  • Published per-request pricing — $0.042 (42 credits) per /v1/instagram/comments page ($42.00 per 1,000 pages) and $0.003 (3 credits) per reply lookup via /v1/instagram/post_comment_replies.
Editorial illustration of a vertical public Instagram post, comment bubbles, and a CSV sheet with anonymous rows
instagram.comments

This tutorial targets backend developers writing structured JSON into databases, APIs, or analytics pipelines—distinct from exporting Instagram comments to CSV or one-off browser downloads. Check live operation parameters on the Instagram comments reference and current telemetry on the status page before scheduling recurring production runs.

Prerequisites and Server-Side Credential Hygiene

All code in this walkthrough targets Node.js 18 LTS or newer using ES Modules (.mjs), where global fetch, URL, and AbortSignal.timeout ship natively with the runtime. You do not need axios, node-fetch, Puppeteer, or an Instagram developer app review to query supported public comment threads.

  • Server runtime only: Never embed SOCIALSCRAPER_API_KEY inside React, Vue, Next.js client components, or browser extensions. Any secret visible in browser DevTools can be copied and spent against your prepaid balance.
  • Backend proxy pattern: If a frontend interface needs to show comments, put this Node.js fetch behind an authenticated server route and cache responses on your backend.
  • Environment configuration: Export SOCIALSCRAPER_API_KEY in your shell or secrets manager. The starter script also reads an optional SOCIALSCRAPER_BASE_URL override that defaults to https://socialmediascraper.org.

Query Parameters and Normalized Comment JSON Fields

Calls go to GET https://socialmediascraper.org/v1/instagram/comments with x-api-key and Idempotency-Key headers. Pass the complete public post or Reel link (including https://) in url; optionally add include_replies=true or the cursor returned by a previous page.

JSON pathTypeNotes for Node.js consumers
data.items[].idstringPlatform comment identifier; keep as a string for database primary keys and reply lookups
data.items[].positionnumber | nullZero- or one-based order within the returned page as exposed by the source
data.items[].textstring | nullRaw public comment body; store as UTF-8 to preserve emojis and multilingual text
data.items[].published_atstring | nullTimestamp when provided; keep null rather than substituting the current clock time
data.items[].authorobjectContains id, handle, and display_name (individual subfields may be null)
data.items[].metricsobjectContains likes and comments counts; preserve null values instead of coercing them to 0
data.cursorstring | nullContinuation token for the next page, or null when no additional page token is returned

Every successful HTTP 200 envelope also includes top-level request_id and meta fields outside data—log request_id in your backend jobs if you need support traceability or billing reconciliation.

Step-by-Step Setup to Scrape Instagram Comments in Node.js

Follow these four steps to execute instagram-comments.mjs (shown immediately below) on one public Instagram post or Reel.

  1. Step 1: Export SOCIALSCRAPER_API_KEY in your server shell

    Set export SOCIALSCRAPER_API_KEY="your_key_here" in your local terminal or server environment. The starter script validates process.env.SOCIALSCRAPER_API_KEY on startup and immediately throws Set SOCIALSCRAPER_API_KEY in your server environment if the variable is missing.

  2. Step 2: Save instagram-comments.mjs locally

    Copy the runnable ES module below into instagram-comments.mjs. For each call, readRecord() builds the request URL, creates a unique randomUUID() for Idempotency-Key, sets a 45-second AbortSignal.timeout(45000), and throws a descriptive error on any non-2xx HTTP status without blindly retrying.

  3. Step 3: Pass a public Instagram URL as a CLI argument

    Invoke node instagram-comments.mjs "https://www.instagram.com/reel/DOq6eV6iIgD" with your chosen public post or Reel link. The script reads process.argv[2] and sends exactly one request to /v1/instagram/comments so your initial run stays strictly bounded.

  4. Step 4: Inspect comments.json and check cursor

    Open the newly written comments.json file containing {source_url, items, cursor}. Inspect the shape of items[0] and confirm whether cursor is non-null before deciding how many additional pages to fetch in a paginated loop.

instagram-comments.mjs
import {writeFile} from 'node:fs/promises';
import {randomUUID} from 'node:crypto';
const key = process.env.SOCIALSCRAPER_API_KEY;
if (!key) throw new Error('Set SOCIALSCRAPER_API_KEY in your server environment');
const base = process.env.SOCIALSCRAPER_BASE_URL || 'https://socialmediascraper.org';
async function readRecord(path, input) {
  const url = new URL(path, base);
  for (const [name, value] of Object.entries(input)) if (value !== undefined) url.searchParams.set(name, String(value));
  const requestKey = randomUUID();
  const response = await fetch(url, {headers: {'x-api-key': key, 'Idempotency-Key': requestKey}, signal: AbortSignal.timeout(45000)});
  if (!response.ok) throw new Error(`HTTP ${response.status}; request key ${requestKey}; inspect your key, balance, input or Retry-After before retrying`);
  const result = await response.json();
  if (!result.data) throw new Error('The response did not contain data');
  return result.data;
}
const url = process.argv[2];
if (!url) throw new Error('Supply a public post or video URL');
const data = await readRecord('/v1/instagram/comments', {url});
const items = Array.isArray(data.items) ? data.items : [];
await writeFile('comments.json', JSON.stringify({source_url:url, items, cursor:data.cursor ?? null}, null, 2), 'utf8');

Extending the Script with Cursor Paging and Child Replies

The starter instagram-comments.mjs fetches a single page by design so you never trigger an unbounded scrape on a viral Reel with 50,000 comments. When you are ready to collect multiple pages, add an explicit maxPages ceiling, issue a new Idempotency-Key for each distinct page, and halt if cursor is null, repeats, or returns zero items:

paginate-instagram-comments.mjs
import {randomUUID} from 'node:crypto';

export async function fetchBoundedInstagramComments(postUrl, {maxPages = 3, includeReplies = false} = {}) {
  const key = process.env.SOCIALSCRAPER_API_KEY;
  const collected = [];
  const seenCursors = new Set();
  let cursor = undefined;

  for (let page = 0; page < maxPages; page += 1) {
    const endpoint = new URL('/v1/instagram/comments', 'https://socialmediascraper.org');
    endpoint.searchParams.set('url', postUrl);
    if (includeReplies) endpoint.searchParams.set('include_replies', 'true');
    if (cursor) endpoint.searchParams.set('cursor', cursor);

    const requestKey = randomUUID();
    const res = await fetch(endpoint, {
      headers: {'x-api-key': key, 'Idempotency-Key': requestKey},
      signal: AbortSignal.timeout(45000),
    });
    if (!res.ok) throw new Error(`Page ${page + 1} failed with HTTP ${res.status} (key=${requestKey})`);

    const {data} = await res.json();
    const batch = Array.isArray(data?.items) ? data.items : [];
    collected.push(...batch);

    if (!data?.cursor || seenCursors.has(data.cursor) || batch.length === 0) break;
    seenCursors.add(data.cursor);
    cursor = String(data.cursor);
  }
  return {items: collected, nextCursor: cursor ?? null};
}

If you only need nested replies under specific high-engagement comments rather than setting include_replies=true on every top-level page, call GET /v1/instagram/post_comment_replies with url, comment_id (as a string), and optional cursor at the standard $0.003 (3 credits) rate.

Troubleshooting HTTP Status Codes and Timeout Errors

Because instagram-comments.mjs prints the exact HTTP status and requestKey whenever response.ok is false, you can diagnose failures without guessing or blindly spending balance.

Status or failureLikely causeHow Node.js should respond
HTTP 400Missing url, malformed link, or invalid Idempotency-Key formatFix the input URL (include https://) before retrying; do not loop
HTTP 401 / 403Wrong, missing, or revoked SOCIALSCRAPER_API_KEYVerify the server environment variable and key permissions in your dashboard
HTTP 402Prepaid USD balance is too low for the $0.042 (42-credit) operation rateStop the worker, top up prepaid balance, then resume from the last saved cursor
HTTP 202Request is still processing or outcome is pendingKeep the request_id and poll GET /v1/requests/{request_id} with the same key
HTTP 429Exceeded default 60 req/min or 5 concurrent in-flight limitSleep for the Retry-After header value, then retry with the same Idempotency-Key
TimeoutError (45s)Upstream response exceeded AbortSignal.timeout(45000)Record the logged requestKey and avoid spinning up concurrent replacement calls

Practical Ways Node.js Apps Store and Process comments.json

Upsert into PostgreSQL or SQLite

Key rows on (source_url, item.id) so repeated campaign refreshes update like counts without creating duplicate rows, and declare metric columns nullable so null never turns into misleading zeros.

Cache behind an internal Express or Next.js route

Store fetched comments.json snapshots in Redis or object storage with a TTL so product managers refreshing an internal dashboard read cached JSON instead of triggering repeat $0.042 API calls.

Feed sanitized text into clustering or LLM tagging

Pass items[].text into your own sentiment or topic classifier while treating comment strings strictly as untrusted user data, retaining author.handle and source_url for audit trails.

Cost Math for Instagram Comment Collection

Unlike standard $0.003 (3-credit) endpoints, GET /v1/instagram/comments carries a published rate of $0.042 (42 credits) per request ($42.00 per 1,000 pages; 1,000 credits = $1). Each paginated cursor request bills separately regardless of how many items Instagram returns on that page.

Collection workloadOperations billedPublished USD cost
Single post sanity check (1 page)1 × instagram.comments$0.042
25 campaign Reels × 4 pages each100 × instagram.comments$4.20
100 posts × 10 pages each1,000 × instagram.comments$42.00
Selective reply expansion (100 reply pages)100 × instagram.post_comment_replies$0.30

New accounts start with 100 starter credits ($0.10, enough for 2 instagram.comments pages), while one-time prepaid USD packs keep identical per-request pricing with zero auto-renewal: $5 (5,000 credits) covers ~119 Instagram comment pages, $20 (20,000 credits) covers ~476 pages, and $50 (50,000 credits) covers ~1,190 pages. Confirm current rates anytime on the pricing page or in pricing.csv.

JSON in Node.js vs CSV Exports and Browser Tools

Stay on Node.js JSON for software pipelines

Keep instagram-comments.mjs when comments feed a backend database, webhook consumer, or AI classifier—JSON preserves nested author and metrics objects, explicit null fields, and exact cursor pagination state.

Coverage Scope and Production Guardrails

  • Public posts and Reels only: Private profiles, restricted communities, and removed comments cannot be retrieved; this API is strictly read-only and does not post or moderate replies.
  • Variable page counts: Instagram determines how many comments appear per cursor page (up to 100 items where returned); a single call rarely covers a large thread.
  • Check live docs and status: Review the Instagram comments operation reference, general documentation, and service status before running automated batches.
  • Compliance: Public visibility does not confer redistribution rights—respect Instagram terms, copyright, and local privacy obligations when storing user comments.

Instagram Comments JavaScript Tutorial Questions

Why should I run this Instagram comments script on a server instead of in the browser?

Browser JavaScript exposes every request header—including x-api-key—inside DevTools network logs. Running instagram-comments.mjs on a Node.js server or backend route keeps SOCIALSCRAPER_API_KEY private and lets you cache results before returning them to users.

Which Node.js version is required to run instagram-comments.mjs?

Node.js 18 or newer is required because the script uses built-in global fetch, AbortSignal.timeout(45000), node:fs/promises, and node:crypto with zero external packages.

Does the starter script pull every comment on an Instagram post automatically?

No. instagram-comments.mjs deliberately fetches one page and writes {source_url, items, cursor} to comments.json so you control spend from the first run. Pass the returned cursor back into a bounded loop (with a maxPages cap) to collect deeper pages.

What is the difference between include_replies and instagram.post_comment_replies?

Setting include_replies=true on GET /v1/instagram/comments ($0.042 / 42 credits per request) asks for reply records alongside the comment page. Calling GET /v1/instagram/post_comment_replies ($0.003 / 3 credits per request) with url and a specific comment_id lets you expand replies selectively for high-value threads at the standard request rate.

Why does readRecord generate a new randomUUID for Idempotency-Key?

Social Media Scraper requires an Idempotency-Key header (8–128 ASCII characters) on every data request. Generating a fresh UUID for each distinct page—and reusing the same key only when retrying that exact failed request—prevents accidental double billing.

Why does the starter script throw on HTTP 429 instead of auto-retrying?

Failing fast prints the exact HTTP status and requestKey so you can verify your key, balance, URL input, or Retry-After window before re-running. In production batch workers, add explicit backoff that sleeps for Retry-After seconds on 429 while reusing the original Idempotency-Key.

How much does it cost to pull comments from 100 Instagram posts?

At $0.042 (42 credits) per request, pulling 1 page per post across 100 posts costs $4.20. If each post averages 5 pages (500 requests total), the batch costs $21.00—always multiply posts by expected pages per post when sizing a budget.

Why do likes or reply counts sometimes appear as null instead of 0?

When Instagram omits or hides a counter on a comment, Social Media Scraper returns null rather than inventing 0. Keep null values intact in JSON and SQL columns so downstream averages are not skewed.

Can this script fetch comments from a private Instagram account?

No. The API only retrieves supported public Instagram posts and Reels and cannot access private accounts, login-only content, or deleted threads.

What should I check before scheduling a large Instagram comments job?

Inspect current input contracts on the Instagram comments doc page, check recent operational metrics on service status, and verify one sample post first to confirm page size and response structure.

When should I use the CSV tutorial instead of this JSON tutorial?

Use this page when your Node.js app stores records in a database or passes JSON to downstream code. Switch to the Instagram comments CSV tutorial when delivering spreadsheet files to non-technical teammates.