Tutorials
Scrape TikTok Comments with JavaScript
Pull public TikTok video comments into local JSON from Node.js 18+ without reverse-engineering X-Bogus request signatures or maintaining headless browsers. Using built-in fetch and GET /v1/tiktok/comments, you get normalized comment records at $0.003 per page with opaque cursor pagination and optional nested reply lookups.
- Zero third-party packages — runs directly on Node.js 18+ with native
fetch,node:fs/promises, andnode:crypto. - Opaque string cursor paging — pass
data.cursorback unchanged as text to collect additional comment pages safely. - Optional sub-thread expansion — fetch nested replies under selected comments via
GET /v1/tiktok/video_comment_replies. - Standard $0.003 (3 credits) per page — $3.00 per 1,000 TikTok comment pages (~1,666 pages per
$5prepaid pack, zero monthly subscription).

tiktok.commentsThis guide covers single-video TikTok comment extraction in JavaScript—saving one normalized comments.json snapshot per command. If you need to iterate across many video URLs under a strict per-video cap, jump to bulk TikTok comment scraping; for a quick one-off browser export using the TikTok Comment Exporter, open the free browser tools hub.
Why Native Node.js Fetch Beats Reverse-Engineering TikTok Web Endpoints
Developers building TikTok giveaway pickers, creator research tools, or comment-question miners frequently start by copying XHR requests from browser DevTools or launching Playwright. Within days, those scripts break on rotating X-Bogus / msToken signatures, slider captchas, and IP throttling.
Calling GET https://socialmediascraper.org/v1/tiktok/comments removes signature engineering and headless Chromium overhead from your Node.js repository. Your script sends a plain HTTPS GET request with x-api-key and Idempotency-Key headers, receives normalized JSON with consistent keys (items[] and cursor), and writes clean UTF-8 output to disk.
Query Options, Opaque Cursors, and TikTok Comment Schema
The starter script targets GET /v1/tiktok/comments, which accepts three query parameters: required url (full https:// public TikTok video link), optional boolean trim, and optional cursor for pagination. When expanding child threads, pair it with GET /v1/tiktok/video_comment_replies (url, comment_id, optional cursor).
| Response field | Expected type | Implementation rule in JavaScript |
|---|---|---|
data.items[].id | string | Keep as a string—TikTok 64-bit IDs overflow Number.MAX_SAFE_INTEGER if cast to Number |
data.items[].text | string | null | Viewer comment copy; preserve raw UTF-8 strings for emoji and non-Latin threads |
data.items[].published_at | string | null | ISO timestamp when available; keep null rather than backfilling execution time |
data.items[].author | object | {id, handle, display_name}—keep author.id as a string when deduplicating giveaway entries |
data.items[].metrics | object | {views, likes, comments, shares}—keep missing counters as null, never coerce null to 0 |
data.cursor | string | null | Treat strictly as an opaque string passed verbatim on the next request; never increment numerically |
Even when a returned TikTok cursor looks like decimal text such as "20" or "40", forward the exact string value unchanged and avoid calculating offsets yourself—cursor formats can change between pages or videos.
Step-by-Step Setup to Scrape TikTok Comments in Node.js
Run the dependency-free tiktok-comments.mjs starter script below on one public TikTok video URL in four quick steps.
Step 1: Configure SOCIALSCRAPER_API_KEY in your Node environment
Run
export SOCIALSCRAPER_API_KEY="your_api_key"inside your server or local shell (never expose the key in client-side frontend code). The script verifiesprocess.env.SOCIALSCRAPER_API_KEYbefore making any network call and throws immediately if unset.Step 2: Create tiktok-comments.mjs
Save the ES module shown below as
tiktok-comments.mjs. ItsreadRecord()helper sendsx-api-keyplus a freshrandomUUID()Idempotency-Key, enforces a 45-secondAbortSignal.timeout(45000), and exits loudly with the HTTP status andrequestKeyon any non-OK response.Step 3: Execute with a public TikTok video URL
Run
node tiktok-comments.mjs "https://www.tiktok.com/@creator/video/7623818255903329566". The script reads the full URL fromprocess.argv[2]and performs a single bounded call to/v1/tiktok/comments.Step 4: Inspect comments.json and evaluate data.cursor
Check the generated
comments.jsonfile ({source_url, items, cursor}). A single page rarely spans an entire viral thread; inspectitems.lengthandcursorbefore deciding whether to loop further.
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/tiktok/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');
Paginating Opaque Cursors and Expanding Comment Replies
Once the single-page starter output looks right, wrap readRecord() in a bounded page loop and optionally call GET /v1/tiktok/video_comment_replies only for top-level comments that report child replies (item.metrics?.comments > 0):
import {randomUUID} from 'node:crypto';
async function callApi(path, query) {
const endpoint = new URL(path, 'https://socialmediascraper.org');
for (const [k, v] of Object.entries(query)) if (v !== undefined) endpoint.searchParams.set(k, String(v));
const requestKey = randomUUID();
const res = await fetch(endpoint, {
headers: {'x-api-key': process.env.SOCIALSCRAPER_API_KEY, 'Idempotency-Key': requestKey},
signal: AbortSignal.timeout(45000),
});
if (!res.ok) throw new Error(`HTTP ${res.status} on ${path} (key=${requestKey})`);
return (await res.json()).data;
}
export async function collectVideoThread(videoUrl, {maxPages = 5, maxReplyThreads = 5} = {}) {
const comments = [];
const visitedCursors = new Set();
let cursor;
for (let i = 0; i < maxPages; i += 1) {
const page = await callApi('/v1/tiktok/comments', {url: videoUrl, cursor});
const rows = Array.isArray(page?.items) ? page.items : [];
comments.push(...rows);
if (!page?.cursor || visitedCursors.has(page.cursor) || rows.length === 0) break;
visitedCursors.add(page.cursor);
cursor = String(page.cursor);
}
const replyCandidates = comments.filter((c) => Number(c.metrics?.comments ?? 0) > 0).slice(0, maxReplyThreads);
const repliesByParent = {};
for (const parent of replyCandidates) {
const replyPage = await callApi('/v1/tiktok/video_comment_replies', {url: videoUrl, comment_id: String(parent.id)});
repliesByParent[String(parent.id)] = Array.isArray(replyPage?.items) ? replyPage.items : [];
}
return {comments, repliesByParent, nextCursor: cursor ?? null};
}
Keeping both maxPages and maxReplyThreads as hard upper bounds makes every run's maximum spend calculable upfront—at most (maxPages + maxReplyThreads) × $0.003.
What JavaScript Developers Build with TikTok Comment JSON
Auditable TikTok giveaway winner selection
Archive timestamped comments.json snapshots, deduplicate entries by string author.id, filter eligible entries cleanly in Node.js, and log the exact winning comment ID so draws stay verifiable.
Audience question and content-hook discovery
Filter items[].text for question marks, price inquiries, or product comparisons across competitor videos to generate data-backed follow-up scripts and FAQ updates.
Creator campaign sentiment datasets
Join saved comment batches with GET /v1/tiktok/post or GET /v1/tiktok/profile inside your own analytics pipeline to weigh audience feedback against video reach.
Handling Rate Limits, HTTP 202, and 64-Bit TikTok IDs
Pacing within 60 req/min and honoring Retry-After
Accounts default to 60 accepted requests per minute and 5 concurrent in-flight requests. The starter script stops cleanly on HTTP 429; if you add retry logic in a long-running worker, wait for Retry-After seconds and resend the exact same Idempotency-Key.
Resolving HTTP 202 and 45-second timeouts
When an endpoint responds with HTTP 202, inspect GET /v1/requests/{request_id} using the same API key rather than launching a fresh paid request. Likewise, log the printed requestKey on AbortSignal.timeout(45000) before retrying.
Preserving 64-bit numeric strings in JavaScript
TikTok comment IDs such as 7623828115408274207 exceed JavaScript's 53-bit safe integer limit (9007199254740991). Always keep id, comment_id, and author.id as strings in JSON, SQL columns, and API query strings.
Choosing Between This Script, Bulk Runs, n8n, and Browser Export
Pick the workflow surface that matches how often you pull TikTok comments and how many videos you need to scan.
| Approach | Best fit | Output format | Guide or tool |
|---|---|---|---|
| Single-video Node.js script | Custom JS apps, giveaways, and quick developer scripts | Local comments.json | This page (tiktok-comments.mjs) |
| Multi-video bounded batch script | Scheduled Node.js jobs across up to 10 videos per batch | Structured multi-video output | Bulk TikTok Comments Tutorial |
| No-code automation flow | Recurring Slack, Sheets, or CRM alerts without Node code | Workflow node JSON items | n8n TikTok Comments Guide |
| Instant browser exporter | One-off manual check without setting up an API key | Downloadable browser export | Free Browser Tools (TikTok Comment Exporter) |
Budgeting TikTok Comment and Reply Requests
Both GET /v1/tiktok/comments and GET /v1/tiktok/video_comment_replies are billed at $0.003 (3 credits) per API request ($3.00 per 1,000 requests; 1,000 credits = $1). You pay per page request—never per returned comment row.
| TikTok comment job | Request breakdown | Total USD cost |
|---|---|---|
| Single video × 5 pages | 5 × tiktok.comments | $0.015 |
| 10 giveaway videos × 10 pages each | 100 × tiktok.comments | $0.30 |
| 50 videos × 10 pages + 250 reply thread checks | 500 comments + 250 replies | $2.25 |
| 1,000 comment pages across campaigns | 1,000 × tiktok.comments | $3.00 |
Accounts open with 100 starter credits ($0.10, ~33 standard pages), and one-time prepaid USD packs keep unit pricing identical at every tier: $5 (5,000 credits) funds ~1,666 standard pages, $20 (20,000 credits) funds ~6,666 pages, and $50 (50,000 credits) funds ~16,666 pages, with no subscriptions or automatic renewals. Inspect full operation rates on the pricing page.
Coverage Boundaries and Responsible Usage
- Public videos with comments open: Private videos, friends-only clips, region-removed posts, and videos with comments turned off return no comment records; read-only access only (no posting, liking, or moderating).
- Partial-thread awareness: A single page is not guaranteed to contain every comment on a video—avoid treating one page sample as a census of all viewers.
- Prompt-injection hygiene: When summarizing TikTok comments with an LLM, delimit comment bodies explicitly and treat every string as untrusted data rather than instructions.
- Operational telemetry and rights: Check service status and API documentation prior to large runs, and observe applicable privacy regulations and platform terms before storing or redistributing user comments.
TikTok Comments JavaScript Tutorial Questions
Can I run tiktok-comments.mjs without installing axios or node-fetch?
Yes. The starter script runs on Node.js 18 or newer using native global fetch, node:fs/promises, and node:crypto (randomUUID), with zero npm install steps.
How do I fetch more than one page of TikTok comments in Node.js?
Read data.cursor from the first response and send it back in the cursor query parameter on your next GET /v1/tiktok/comments call—with a fresh Idempotency-Key and a hard maxPages cap—until cursor is null, repeats, or items is empty.
Why should data.cursor be treated as an opaque string instead of a counter?
Even when a cursor looks like decimal digits (such as "20"), TikTok pagination tokens are governed upstream and can change format. Forwarding the exact string returned by the previous response prevents skipped or duplicated pages.
How do I retrieve replies beneath a specific TikTok comment?
Call GET /v1/tiktok/video_comment_replies ($0.003 / 3 credits per request) with the video's url and the parent comment's id passed as string parameter comment_id, plus optional cursor for multi-page reply threads.
Why must TikTok comment IDs stay strings in JavaScript?
TikTok uses 64-bit numeric identifiers that exceed JavaScript's safe integer range (2^53 - 1). Coercing id or comment_id with Number() silently corrupts the trailing digits and breaks reply lookups and database deduplication.
How much does it cost to pull 1,000 pages of TikTok comments?
At $0.003 (3 credits) per request, 1,000 comment pages cost $3.00—comfortably inside a single $5 one-time prepaid pack (5,000 credits), with no recurring subscription required.
Can I use this Node.js script to pick a fair TikTok giveaway winner?
Yes. Save the fetched pages to a timestamped JSON file, deduplicate entries by author.id (kept as a string), apply your eligibility rules in code, and select a random index using Node's node:crypto randomInt().
Should I call /v1/tiktok/comments directly from browser JavaScript?
No. Keep SOCIALSCRAPER_API_KEY on a Node.js backend, cron worker, or server route—shipping API keys inside frontend bundles lets anyone copy your credentials from browser DevTools.
What happens if a TikTok video is private or has comments disabled?
Social Media Scraper only accesses supported public content. Private, removed, or comment-disabled videos will return an empty items array or an explicit error status rather than bypassing privacy controls.
How do I scrape TikTok comments across dozens of videos in one run?
Follow the bulk TikTok comments tutorial, which enforces strict video-count and pages-per-video caps so multi-URL runs stay within your budget and rate limits.
Is there a way to export TikTok comments without writing JavaScript?
Yes. For quick manual exports open the TikTok Comment Exporter under free browser tools, or build recurring no-code workflows with the n8n TikTok comments integration.