JavaScript / TypeScript
Typed events, promises and an event-emitter API.
Requirements
Node.js 22.19+.
Installation
npm install piratetok-live-js
Save the quickstart as reader.mjs and run node reader.mjs.
Quickstart
Replace username_here with the username of an account that is currently live.
import { TikTokLiveClient, EventType } from "piratetok-live-js";
const client = new TikTokLiveClient("username_here");
client.on(EventType.chat, (message) => {
console.log(`${message.user?.nickname ?? "?"}: ${message.content}`);
});
client.on("error", console.error);
process.once("SIGINT", () => client.disconnect());
const roomId = await client.connect();
console.log(`Connected to room ${roomId}`);
Connection lifecycle
connect() resolves with the room ID after the first successful WebSocket handshake. Events and reconnects continue in the background. Call disconnect() to stop. If the first handshake never succeeds, the promise rejects. Subscribe to error before connecting.
Configuration
const client = new TikTokLiveClient("username_here")
.cdnEU() // EU CDN endpoint
.cdnUS() // US CDN endpoint
.cdn("webcast-ws.custom.tiktok.com") // custom CDN host
.timeout(15_000) // HTTP timeout in ms (default 10000)
.maxRetries(10) // consecutive failed reconnects before giving up (default 5)
.staleTimeout(90_000) // reconnect after N ms of silence (default 60000)
.heartbeatInterval(10_000) // WSS heartbeat in ms (default 10000)
.proxy("socks5://host:port") // proxy URL (HTTP/HTTPS/SOCKS5)
.compress(false) // disable gzip compression for WSS payloads (default true)
.userAgent("Mozilla/...") // override random UA rotation with a fixed user-agent
.cookies("sessionid=xxx; sid_tt=xxx") // session cookies for 18+ room info
.language("en") // override detected system language (two-letter code)
.region("US"); // override detected system region (two-letter code)
Room info (optional, separate call)
import { checkOnline, fetchRoomInfo } from "piratetok-live-js";
const { roomId } = await checkOnline("username_here");
const info = await fetchRoomInfo(roomId);
// 18+ rooms
const restrictedInfo = await fetchRoomInfo(roomId, 10_000, "sessionid=abc; sid_tt=abc");
Viewers
The top-viewers box (usually top 3) rides the WSS feed — no cookies:
import { topViewers } from "piratetok-live-js";
client.on(EventType.roomUserSeq, (data) => {
for (const c of topViewers(data)) console.log(c.rank, c.user?.nickname, c.score);
});
The full roster (the web viewer panel) is a separate HTTP call. TikTok requires session
cookies for this one call — without them it throws SessionRequiredError:
import { checkOnline, fetchRoomAudience } from "piratetok-live-js";
const { roomId, anchorId } = await checkOnline("username_here");
const audience = await fetchRoomAudience(roomId, anchorId, "sessionid=abc; sid_tt=abc");
// audience.total, audience.anonymous, audience.viewers[].{rank, username, nickname, ...}
Pass undefined as anchorId to resolve it from room info (one extra request).
Helpers
Three stateful helpers for common patterns. Exported from the main package, never imported by the core pipeline.
import { GiftStreakTracker, LikeAccumulator, ProfileCache } from "piratetok-live-js";
// GiftStreakTracker — computes per-event gift deltas from TikTok's running totals
const tracker = new GiftStreakTracker();
client.on(EventType.gift, (data) => {
const streak = tracker.process(data);
// streak.eventGiftCount, streak.totalDiamondCount, streak.isFinal, ...
});
// LikeAccumulator — monotonizes TikTok's inconsistent total_like_count
const likes = new LikeAccumulator();
client.on(EventType.like, (data) => {
const stats = likes.process(data);
// stats.totalLikeCount (never goes backwards), stats.accumulatedCount
});
// ProfileCache — TTL-cached profile scraping with ttwid management
const cache = new ProfileCache({ ttlMs: 300_000, proxy: "socks5://host:port" });
const profile = await cache.fetch("username_here");
// profile.uniqueId, profile.nickname, profile.followerCount, ...
Protocol reference
The basic LIVE connection uses an anonymous ttwid cookie. Session cookies may be needed for restricted room metadata or the full audience roster. These are separate calls from the event stream.
- WebSocket contract
- Room metadata
- Audience endpoint
- Authentication and connection lifecycle
- Troubleshooting
Source and license
Public source and examples · 0BSD license