Tutorial · TikTok · Node.js

TikTok video views and likes to CSV with Node.js

To get TikTok video stats with Node.js, call /v1/tiktok/posts/{post} for each link with the built-in fetch and append data.counts to a CSV. The script below needs no npm packages and stamps every row with the time it was checked.

Short answer. Run node tiktok-video-stats.mjs links.txt with HANDLEHAUL_API_KEY set and open video_stats.csv: views, likes, comments, shares, saves, duration, author and caption per video. 1,000 videos cost $1.40 to $0.80; links that no longer exist are free.

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} (see the TikTok post API docs), retries on 429 using Retry-After, and stops with a clear message on any other error. Save it as tiktok-video-stats.mjs.

tiktok-video-stats.mjs
// Save views, likes, comments, shares and saves for a list of TikTok videos to CSV.
// Usage: node tiktok-video-stats.mjs links.txt   (one video link or id per line)
// Needs Node 18+ (built-in fetch) and HANDLEHAUL_API_KEY in the environment. No dependencies.
import { readFileSync, 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 = ["input", "id", "url", "created_at", "views", "likes", "comments", "shares", "saves",
  "duration_seconds", "author", "author_followers", "caption", "checked_at", "error"];
const SKIP = new Set(["user_not_found", "private_account"]); // note these and go on (failed calls are free)

const file = process.argv[2];
if (!file) fail("Usage: node tiktok-video-stats.mjs links.txt");
const lines = readFileSync(file, "utf8").split(/\r?\n/).map((l) => l.trim());
const links = [...new Set(lines.filter((l) => l && !l.startsWith("#")))];
const out = "video_stats.csv";

writeFileSync(out, "" + csvLine(FIELDS)); // the BOM lets Excel read emoji and accents
let done = 0, credits = 0;
for (const link of links) {
  const checked_at = new Date().toISOString().replace(/\.\d+Z$/, "Z");
  let body;
  try {
    body = await get(`/v1/tiktok/posts/${encodeURIComponent(link)}`);
  } catch (e) {
    if (!SKIP.has(e.code)) fail(`Stopped: ${e.message}\n${done} videos saved in ${out}`);
    appendFileSync(out, csvLine(FIELDS.map((f) => ({ input: link, checked_at, error: e.code })[f])));
    console.log(`${link}: ${e.code}`);
    continue;
  }
  const p = body.data;
  credits += body.meta.credits_charged ?? 0;
  const row = {
    ...p, ...p.counts, input: link, author: p.author.handle,
    author_followers: p.author.counts?.followers, checked_at, error: "",
  };
  appendFileSync(out, csvLine(FIELDS.map((f) => row[f])));
  done++;
  console.log(`${p.id}: ${p.counts.views} views, ${p.counts.likes} likes`);
}
console.log(`Saved ${done} of ${links.length} videos to ${out} (${credits} credits)`);
Tested 2026-12-02 against the documented API responses on Node.js 26, using only Node 18 features. Run: node tiktok-video-stats.mjs links.txt

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-video-stats.mjs. Copy the script above into tiktok-video-stats.mjs, and put your input in links.txt, one item per line.
  5. Run it. Run node tiktok-video-stats.mjs links.txt. Progress prints as it goes; the output file is written as rows arrive, so an interrupted run keeps what it fetched.

Example links.txt:

links.txt
https://www.tiktok.com/@river_wren29/video/7300000000000000123
7300000000000000456
Terminal
export HANDLEHAUL_API_KEY=kd_live_...   # your key from the dashboard
node --version                  # v18 or newer
node tiktok-video-stats.mjs links.txt
On Windows PowerShell, set the key with $env:HANDLEHAUL_API_KEY="kd_live_...".

How it works

One call per video. The script calls /v1/tiktok/posts/{post} with the video id, or the full link URL-encoded into the path (https%3A%2F%2Fwww.tiktok.com%2F…). Both work; the script encodes whatever is on the line.

The counts. data.counts holds views, likes, comments, shares and saves. The script also keeps duration_seconds, the caption, the author’s handle and follower count (data.author.counts.followers).

Snapshots. Every row gets a checked_at time in UTC. Run the script on a schedule and keep each day’s file to see how a video’s numbers grow.

Missing videos. A video that does not exist answers 404 with the code user_not_found (that is the code the API uses for posts too). The script writes it in the error column and goes on, and the call is free.

Many videos from one account? /v1/tiktok/users/{user}/posts returns a page of an account’s videos with the same counts in one call, which costs far less than one call per video.

What it costs

Every successful call is 1 credit, at $1.40 to $0.80 per 1,000 calls. One call per video that exists. Videos that do not exist and answers from the cache are free.

Calls and cost for tiktok video views and likes to csv
JobCallsCost
100 videos100$0.14 to $0.080
1,000 videos1,000$1.40 to $0.80
100 videos, daily for 30 days3,000$4.20 to $2.40

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
7300000000000000123: 538234 views, 32294 likes
7300000000000000456: user_not_found
Saved 1 of 2 videos to video_stats.csv (1 credits)
video_stats.csv
input,id,url,created_at,views,likes,comments,shares,saves,duration_seconds,author,author_followers,caption,checked_at,error
https://www.tiktok.com/@river_wren29/video/7300000000000000123,7300000000000000123,https://www.tiktok.com/@river_wren29/video/7300000000000000123,2026-07-30T00:53:20.000Z,538234,32294,1076,538,1615,18,river_wren29,579298,Sample post 124 by @river_wren29 #pixel #fyp,2026-12-02T09:00:00Z,

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
404 user_not_foundThe video does not exist or was deletedThe script writes a row with the error code and goes on (failed calls are free).
403 private_accountThe video belongs to a private accountThe script writes a row with the error code and goes on (failed calls are free).
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 { data: p } = await hh.tiktok.post("7300000000000000123");
console.log(p.counts.views, p.counts.likes, p.counts.shares);
Source and reference: handlehaul-js on GitHub.

Next steps

TikTok video views and likes to CSV with Node.js: questions

Is there an npm TikTok scraper I can use instead?
The official SDK (npm install handlehaul) wraps the same endpoint as hh.tiktok.post() with types and automatic retries; see the SDK block above. It calls the API, so it does not break when TikTok changes its web page.
Why URL-encode the link into the path?
The post endpoint takes the id or the full link in the path. encodeURIComponent turns /, : and @ into %2F, %3A and %40 so the link stays one path segment.
Can I get stats for every video of an account?
Use /v1/tiktok/users/{user}/posts: one call returns a page of the account’s videos with the same counts, which is far cheaper than one call per video. Then use this script for single videos you track.
How do I keep a history instead of overwriting the file?
Change out to include the date, for example `video_stats_${new Date().toISOString().slice(0, 10)}.csv`, and run it daily from cron.

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.