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, andAbortSignal.timeout(45000). - Structured comments.json output — saves
{source_url, items, cursor}straight fromGET /v1/instagram/comments. - Safe fail-fast execution — generates a fresh
randomUUID()Idempotency-Keyper call and exits cleanly on non-2xx HTTP statuses. - Published per-request pricing — $0.042 (42 credits) per
/v1/instagram/commentspage ($42.00per 1,000 pages) and $0.003 (3 credits) per reply lookup via/v1/instagram/post_comment_replies.

instagram.commentsThis 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_KEYinside 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_KEYin your shell or secrets manager. The starter script also reads an optionalSOCIALSCRAPER_BASE_URLoverride that defaults tohttps://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 path | Type | Notes for Node.js consumers |
|---|---|---|
data.items[].id | string | Platform comment identifier; keep as a string for database primary keys and reply lookups |
data.items[].position | number | null | Zero- or one-based order within the returned page as exposed by the source |
data.items[].text | string | null | Raw public comment body; store as UTF-8 to preserve emojis and multilingual text |
data.items[].published_at | string | null | Timestamp when provided; keep null rather than substituting the current clock time |
data.items[].author | object | Contains id, handle, and display_name (individual subfields may be null) |
data.items[].metrics | object | Contains likes and comments counts; preserve null values instead of coercing them to 0 |
data.cursor | string | null | Continuation 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.
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 validatesprocess.env.SOCIALSCRAPER_API_KEYon startup and immediately throwsSet SOCIALSCRAPER_API_KEY in your server environmentif the variable is missing.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 uniquerandomUUID()forIdempotency-Key, sets a 45-secondAbortSignal.timeout(45000), and throws a descriptive error on any non-2xx HTTP status without blindly retrying.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 readsprocess.argv[2]and sends exactly one request to/v1/instagram/commentsso your initial run stays strictly bounded.Step 4: Inspect comments.json and check cursor
Open the newly written
comments.jsonfile containing{source_url, items, cursor}. Inspect the shape ofitems[0]and confirm whethercursoris non-null before deciding how many additional pages to fetch in a paginated loop.
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:
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 failure | Likely cause | How Node.js should respond |
|---|---|---|
HTTP 400 | Missing url, malformed link, or invalid Idempotency-Key format | Fix the input URL (include https://) before retrying; do not loop |
HTTP 401 / 403 | Wrong, missing, or revoked SOCIALSCRAPER_API_KEY | Verify the server environment variable and key permissions in your dashboard |
HTTP 402 | Prepaid USD balance is too low for the $0.042 (42-credit) operation rate | Stop the worker, top up prepaid balance, then resume from the last saved cursor |
HTTP 202 | Request is still processing or outcome is pending | Keep the request_id and poll GET /v1/requests/{request_id} with the same key |
HTTP 429 | Exceeded default 60 req/min or 5 concurrent in-flight limit | Sleep 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 workload | Operations billed | Published USD cost |
|---|---|---|
| Single post sanity check (1 page) | 1 × instagram.comments | $0.042 |
| 25 campaign Reels × 4 pages each | 100 × instagram.comments | $4.20 |
| 100 posts × 10 pages each | 1,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.
Switch to CSV or browser tools for analyst handoffs
Follow the Instagram comments to CSV tutorial when stakeholders want formula-escaped spreadsheets, or try the free Instagram comment exporter for occasional one-off browser checks without running Node.js.
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.