Tutorial · Instagram · Node.js

Scrape Instagram comments to CSV with Node.js

To export Instagram comments with Node.js, walk /v1/instagram/posts/{post}/comments page by page with the built-in fetch, fetch replies only where reply_count is above zero, and append rows to a CSV. The script below uses one small async generator for both comments and replies.

Short answer. Run node instagram-comments.mjs https://www.instagram.com/p/C9xYzAbCdEf/ newest with HANDLEHAUL_API_KEY set and open comments_C9xYzAbCdEf.csv. About 15 comments per call: 1,000 comments take about 67 calls, $0.094 to $0.054, plus reply pages.

Facts checked 2 December 2026. Prices change: follow the links before you decide.

What you need

  • An API key. Sign up and create one in the dashboard. A sandbox key (kd_test_) returns sample data for free, so you can run the script before you spend anything.
  • Node.js 18 or newer, for the built-in fetch. No npm packages: the CSV is written by hand with proper quoting.
  • The key in HANDLEHAUL_API_KEY. The script reads it from the environment, so the key never sits in your code or your repository.
  • Public Instagram posts. The API returns public data only: no logins, no private accounts, no DMs.

The script

It calls GET /v1/instagram/posts/{post}/comments and GET /v1/instagram/comments/{comment}/replies (see the Instagram comments API docs), retries on 429 using Retry-After, and stops with a clear message on any other error. Save it as instagram-comments.mjs.

instagram-comments.mjs
// Export every comment on a public Instagram post (and the replies) to CSV.
// Usage: node instagram-comments.mjs <shortcode or post URL> [top|newest] [max_pages]
// Needs Node 18+ (built-in fetch) and HANDLEHAUL_API_KEY in the environment. No dependencies.
import { writeFileSync, appendFileSync } from "node:fs";

const API = "https://api.handlehaul.com";
const KEY = process.env.HANDLEHAUL_API_KEY;
if (!KEY) fail("Set HANDLEHAUL_API_KEY first, e.g. export HANDLEHAUL_API_KEY=kd_live_...");

function fail(message) {
  console.error(message);
  process.exit(1);
}

class ApiError extends Error {
  constructor(status, code, message) {
    super(`HTTP ${status} ${code}: ${message}`);
    this.status = status;
    this.code = code;
  }
}

const sleep = (seconds) => new Promise((resolve) => setTimeout(resolve, seconds * 1000));

// One API call. Waits and retries on 429 (honouring Retry-After) and on 502/503/504,
// throws ApiError for any other error. Failed calls and 429 answers are not charged.
async function get(path, params = {}) {
  const url = new URL(API + path);
  for (const [k, v] of Object.entries(params)) url.searchParams.set(k, v);
  for (let attempt = 0; ; attempt++) {
    const res = await fetch(url, { headers: { "X-Api-Key": KEY } });
    if ([429, 502, 503, 504].includes(res.status) && attempt < 5) {
      const wait = Number(res.headers.get("retry-after")) || 2 ** attempt;
      console.error(`  HTTP ${res.status}, retrying in ${wait}s`);
      await res.arrayBuffer();
      await sleep(wait);
      continue;
    }
    const body = await res.json().catch(() => ({}));
    if (res.ok) return body;
    const err = body.error ?? {};
    throw new ApiError(res.status, err.code ?? "unknown", err.message ?? res.statusText);
  }
}

// CSV by hand (RFC 4180): quote a cell when it holds a comma, a quote or a line break.
const cell = (v) => {
  const s = v == null ? "" : String(v);
  return /[",\r\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
};
const csvLine = (values) => values.map(cell).join(",") + "\r\n";

const FIELDS = ["id", "parent_id", "created_at", "username", "full_name", "like_count", "reply_count", "text"];
const MAX_REPLY_PAGES = 5; // per comment; set 0 to skip replies

// Yields one page at a time, following pagination.next_cursor.
async function* walk(path, params, maxPages) {
  params = { ...params };
  for (let i = 0; i < maxPages; i++) {
    const body = await get(path, params);
    yield body;
    if (!body.pagination.has_more) return;
    params.cursor = body.pagination.next_cursor;
  }
}

const row = (c, parentId = "") => [c.id, parentId, c.created_at, c.author.username, c.author.full_name,
  c.like_count, c.reply_count ?? 0, c.text];

const args = process.argv.slice(2);
if (!args[0]) fail("Usage: node instagram-comments.mjs <shortcode or post URL> [top|newest] [max_pages]");
// https://www.instagram.com/p/C9xYzAbCdEf/ -> C9xYzAbCdEf
const post = args[0].match(/\/(?:p|reels?|tv)\/([\w-]+)/)?.[1] ?? args[0];
const sort = args[1] ?? "top";
const maxPages = Number(args[2] ?? 20); // about 15 comments a page
const out = `comments_${post.replace(/[^\w-]/g, "_")}.csv`;
const path = `/v1/instagram/posts/${encodeURIComponent(post)}/comments`;

writeFileSync(out, "" + csvLine(FIELDS)); // the BOM lets Excel read emoji and accents
let rows = 0, calls = 0, credits = 0;
try {
  for await (const page of walk(path, { sort }, maxPages)) {
    calls++;
    credits += page.meta.credits_charged ?? 0;
    for (const c of page.data) {
      appendFileSync(out, csvLine(row(c)));
      rows++;
      if ((c.reply_count ?? 0) > 0 && MAX_REPLY_PAGES > 0) {
        const repliesPath = `/v1/instagram/comments/${c.id}/replies`;
        for await (const rpage of walk(repliesPath, { post }, MAX_REPLY_PAGES)) {
          calls++;
          credits += rpage.meta.credits_charged ?? 0;
          appendFileSync(out, rpage.data.map((r) => csvLine(row(r, c.id))).join(""));
          rows += rpage.data.length;
        }
      }
    }
    console.log(`${rows} comments and replies so far`);
  }
} catch (e) {
  fail(`Stopped: ${e.message}\n${rows} rows saved in ${out}`);
}
console.log(`Saved ${rows} rows to ${out} (${calls} calls, ${credits} credits)`);
Tested 2026-12-02 against the documented API responses on Node.js 26, using only Node 18 features. Run: node instagram-comments.mjs https://www.instagram.com/p/C9xYzAbCdEf/ newest

Run it

  1. Get an API key. Sign up at api.handlehaul.com/signup and create a key. A sandbox key (kd_test_) returns sample data for free while you test.
  2. Set HANDLEHAUL_API_KEY. Export the key as the environment variable HANDLEHAUL_API_KEY so it never sits in the code.
  3. Check Node.js. Run node --version and make sure it is 18 or newer, for the built-in fetch. No npm packages are needed.
  4. Save the script as instagram-comments.mjs. Copy the script above into instagram-comments.mjs.
  5. Run it. Run node instagram-comments.mjs https://www.instagram.com/p/C9xYzAbCdEf/ newest. Progress prints as it goes; the output file is written as rows arrive, so an interrupted run keeps what it fetched.
Terminal
export HANDLEHAUL_API_KEY=kd_live_...   # your key from the dashboard
node --version                  # v18 or newer
node instagram-comments.mjs https://www.instagram.com/p/C9xYzAbCdEf/ newest
On Windows PowerShell, set the key with $env:HANDLEHAUL_API_KEY="kd_live_...".

How it works

Paging. /v1/instagram/posts/{post}/comments returns about 15 comments a page. The script follows pagination.next_cursor until has_more is false or max_pages is reached (20 by default, so about 300 comments).

Sort. top (the default) or newest, passed as ?sort=. Use newest when you collect comments on a schedule and only need what is new.

Replies only where they exist. Each comment has a reply_count. Only when it is above zero does the script call /v1/instagram/comments/{comment}/replies with ?post= set to the shortcode, so you never pay for empty reply pages. MAX_REPLY_PAGES caps it per comment; set it to 0 to skip replies.

parent_id. The script fills this column with the id of the comment a reply answers, so you can rebuild threads in a spreadsheet. Top-level comments leave it empty.

Links work. Paste the post or reel link or just the shortcode; the script pulls the shortcode out of instagram.com/p/…, /reel/… and /tv/… links.

What it costs

Every successful call is 1 credit, at $1.40 to $0.80 per 1,000 calls. One call per page of about 15 comments, plus one call per page of replies for each comment that has replies. Failed calls and private accounts are free.

Calls and cost for export instagram comments to csv
JobCallsCost
100 comments7$0.0098 to $0.0056
1,000 comments67$0.094 to $0.054
10,000 comments667$0.93 to $0.53

The script makes one call at a time, well under the account limit of 10 to 30 requests per second. Each response says what it cost in meta.credits_charged, and the script adds those up in its last line.

Sample output

An example run with example values, not a real export. Field names and shapes are the ones in the API docs.

Terminal
16 comments and replies so far
31 comments and replies so far
46 comments and replies so far
Saved 46 rows to comments_C9xYzAbCdEf.csv (4 calls, 4 credits)
comments_C9xYzAbCdEf.csv
id,parent_id,created_at,username,full_name,like_count,reply_count,text
782890015575457736,,2026-11-28T12:00:00.000Z,studio.atelier21,Studio Atelier,76,0,Love this!
782890015575457801,,2026-11-28T12:04:00.000Z,coffee.place,Coffee Place,12,1,"Where was this, Lisbon?"
782890015575457950,782890015575457801,2026-11-28T12:30:00.000Z,studio.atelier21,Studio Atelier,3,0,Yes!

Common errors

Errors come back as { "error": { "code", "message", "request_id" } } with an HTTP status. Failed calls are never charged. Full list: error codes.

Errors this script can meet and what it does
Status and codeWhenWhat the script does
403 private_accountThe post belongs to a private accountStops. Free.
404The post does not exist or was deletedStops. Free. Check the shortcode.
400 invalid_cursorA cursor from another postStops. Start again without a cursor.
401 invalid_api_keyThe key is missing, wrong or revokedStops with the message. Check the variable with echo $HANDLEHAUL_API_KEY.
402 insufficient_creditsThe account is out of creditsStops. Rows already fetched stay in the file.
429 rate_limitedToo many requests per secondWaits for Retry-After and retries, up to 5 times. Not charged.
502 / 503 / 504Data temporarily unavailable or slowRetries with a growing wait (1, 2, 4, 8, 16 s). Failed calls are free.

The same job with the SDK

If you would rather not maintain the HTTP code, the official JavaScript SDK (npm install handlehaul) does the paging, retries 429 for you and raises typed errors. The script above is the same job with every request visible.

Node SDK
// npm install handlehaul
import { HandleHaul } from "handlehaul";

const hh = new HandleHaul(); // reads HANDLEHAUL_API_KEY
for await (const c of hh.instagram.postComments.iterate("C9xYzAbCdEf", { sort: "newest", maxPages: 20 })) {
  console.log(c.author.username, c.like_count, c.text);
}
Source and reference: handlehaul-js on GitHub.

Next steps

Export Instagram comments to CSV with Node.js: questions

How does the walk() generator work?
It calls the endpoint, yields the page, and if has_more is true sets cursor to next_cursor and loops, up to a page limit. Because it is lazy, breaking out of the for await loop stops further calls, and further charges.
Does it work with reels?
Yes. Reels are posts: paste a /reel/… link or its shortcode and the script reads the same comments endpoint.
How do I skip replies to save calls?
Set MAX_REPLY_PAGES to 0. The CSV then has top-level comments only, and the cost is one call per page of about 15.
Can I stream the rows to a database instead of a CSV?
Yes. Replace the appendFileSync calls with an insert into your database, using the comment id as the key so re-runs update rows instead of duplicating them.

Run it on your own list

One key for Instagram and TikTok. $1.40 to $0.80 per 1,000 calls; failed calls are free.

Want to test first? Sandbox keys are free and unlimited, with sample data in the live schema.