Tutorial · TikTok · Node.js

Scrape TikTok comments to CSV with Node.js

To export TikTok comments with Node.js, walk /v1/tiktok/posts/{post}/comments with the built-in fetch, keep the ids you have seen in a Set, and append new comments to a CSV. The script below does that in one file, with replies as an option.

Short answer. Run node tiktok-comments.mjs https://www.tiktok.com/@user/video/7300000000000000123 with HANDLEHAUL_API_KEY set and open comments_7300000000000000123.csv. About 20 comments per call: 1,000 comments take 50 calls, $0.070 to $0.040.

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 TikTok videos. The API returns public data only: no logins, no private accounts, no DMs.

The script

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

tiktok-comments.mjs
// Export every comment on a TikTok video to CSV, without duplicates.
// Usage: node tiktok-comments.mjs <video link or id> [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", "handle", "nickname", "like_count", "reply_count", "text"];
const INCLUDE_REPLIES = false; // true also fetches replies (about 3 per call) for comments that have them
const MAX_REPLY_PAGES = 10;    // per comment

// 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 [post, maxArg] = process.argv.slice(2);
if (!post) fail("Usage: node tiktok-comments.mjs <video link or id> [max_pages]");
const maxPages = Number(maxArg ?? 50); // about 20 comments a page
const videoId = post.match(/\/(?:video|photo)\/(\d+)/)?.[1] ?? post.replace(/[^0-9A-Za-z_-]/g, "_").slice(-40);
const out = `comments_${videoId}.csv`;
const path = `/v1/tiktok/posts/${encodeURIComponent(post)}/comments`;

const seen = new Set();
let calls = 0, repeats = 0, credits = 0;
function save(comments) {
  for (const c of comments) {
    if (seen.has(c.id)) { // TikTok can repeat a few comments on the next page
      repeats++;
      continue;
    }
    seen.add(c.id);
    appendFileSync(out, csvLine([c.id, c.parent_id ?? "", c.created_at, c.author.handle, c.author.nickname,
      c.like_count, c.reply_count ?? 0, c.text]));
  }
}

writeFileSync(out, "" + csvLine(FIELDS)); // the BOM lets Excel read emoji and accents
try {
  for await (const page of walk(path, {}, maxPages)) {
    calls++;
    credits += page.meta.credits_charged ?? 0;
    save(page.data);
    if (INCLUDE_REPLIES) {
      for (const c of page.data.filter((c) => (c.reply_count ?? 0) > 0)) {
        for await (const rpage of walk(`/v1/tiktok/comments/${c.id}/replies`, { post }, MAX_REPLY_PAGES)) {
          calls++;
          credits += rpage.meta.credits_charged ?? 0;
          save(rpage.data);
        }
      }
    }
    console.log(`${seen.size} comments so far`);
  }
} catch (e) {
  fail(`Stopped: ${e.message}\n${seen.size} comments saved in ${out}`);
}
console.log(`Saved ${seen.size} comments to ${out} (${repeats} repeats dropped, ${calls} calls, ${credits} credits)`);
Tested 2026-12-02 against the documented API responses on Node.js 26, using only Node 18 features. Run: node tiktok-comments.mjs https://www.tiktok.com/@river_wren29/video/7300000000000000123

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 tiktok-comments.mjs. Copy the script above into tiktok-comments.mjs.
  5. Run it. Run node tiktok-comments.mjs https://www.tiktok.com/@river_wren29/video/7300000000000000123. 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 tiktok-comments.mjs https://www.tiktok.com/@river_wren29/video/7300000000000000123
On Windows PowerShell, set the key with $env:HANDLEHAUL_API_KEY="kd_live_...".

How it works

Paging. /v1/tiktok/posts/{post}/comments returns about 20 top-level comments a page, in TikTok’s order. The script follows pagination.next_cursor until has_more is false or max_pages is reached (50 by default, so about 1,000 comments).

Duplicates. TikTok can repeat a few comments from one page on the next. The script keeps a set of comment ids, writes each id once and reports how many repeats it dropped.

Replies. Set INCLUDE_REPLIES to true and, for each comment with reply_count above zero, the script calls /v1/tiktok/comments/{comment}/replies with ?post=. Replies come about 3 a page, so they cost more per row; on a reply, parent_id is the comment it answers.

Comments turned off. A video with comments off answers an empty page, so the file has only its header row.

Link or id. Paste the video link or the bare id. The output file is named after the video id.

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 20 comments; replies are one call per page of about 3. Failed calls and pages from the cache are free.

Calls and cost for export tiktok comments to csv
JobCallsCost
100 comments5$0.0070 to $0.0040
1,000 comments50$0.070 to $0.040
1,000 replies (about 3 a page)334$0.47 to $0.27

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
20 comments so far
39 comments so far
58 comments so far
Saved 58 comments to comments_7300000000000000123.csv (2 repeats dropped, 3 calls, 3 credits)
comments_7300000000000000123.csv
id,parent_id,created_at,handle,nickname,like_count,reply_count,text
7300000000000010123,,2026-11-30T00:53:20.000Z,aurora_cedar12,Aurora Cedar,50,0,Sample comment 1

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
404The video does not exist or was deletedStops. Free.
403 private_accountThe video belongs to a private accountStops. Free.
400 invalid_cursorA cursor from another videoStops. 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
const seen = new Set();
for await (const c of hh.tiktok.postComments.iterate("7300000000000000123", { maxPages: 50 })) {
  if (seen.has(c.id)) continue;
  seen.add(c.id);
  console.log(c.author.handle, c.text);
}
Source and reference: handlehaul-js on GitHub.

Next steps

Export TikTok comments to CSV with Node.js: questions

Why keep the ids in a Set?
TikTok can repeat a few comments from one page on the next. seen.has(c.id) is a constant-time check, so the script writes each comment once even on videos with tens of thousands of comments.
Does it fetch replies?
Not by default. Set INCLUDE_REPLIES = true and it calls the replies endpoint for each comment with reply_count above zero, about 3 replies per call. On a reply row, parent_id is the comment it answers.
Can I stop after the first few hundred comments?
Yes: pass a page limit, for example node tiktok-comments.mjs 7300000000000000123 10 for about 200 comments. Each page is one call, so the limit is also a spending cap.
Which comment fields are available besides the ones in the CSV?
Each comment also has the author’s id, sec_uid, avatar_url, is_verified and profile url, plus post_id. Add them to the row in save() if you need 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.