Node.js & TypeScript SDK: Official TrackSERPs Client
@trackserps/sdk is the official TypeScript client for the TrackSERPs REST API. It has no runtime dependencies, ships ESM and CommonJS builds with types generated from the OpenAPI spec, retries 429 and 5xx responses, adds idempotency keys to POST requests, turns list endpoints into async iterators, waits for one-off lookups, and verifies webhook signatures. It is meant for server-side Node, not browsers.
Key facts
- Node's global fetch has been enabled by default since Node 18 and is documented as no longer experimental since Node 21, so the SDK needs no HTTP dependency.Source: nodejs.org
- One-off rank lookups normally take 10 to 20 minutes, which is why the SDK's waitFor polls once a minute by default.Source: trackserps.com
- Manual runs are limited to one per project every 10 minutes, and the resulting 429 run_too_soon can carry a Retry-After of up to 600 seconds.Source: trackserps.com
- Reusing an Idempotency-Key with a different request body returns 409 idempotency_mismatch instead of repeating the work.Source: trackserps.com
What the SDK gives you over raw fetch
@trackserps/sdk is a thin, typed layer over the TrackSERPs REST API. Every method maps to one endpoint in the OpenAPI spec, and the TypeScript types are generated from that spec, so a field renamed in the API is a compile error rather than a runtime surprise.
Our position: use the SDK for the plumbing it handles well (pagination, retries, idempotency keys, lookup waiting, webhook verification) and hand-write the one piece it leaves out, polling a project run.
What you get:
- Zero runtime dependencies. It uses the global
fetch, which Node has enabled by default since version 18. - ESM and CommonJS builds, each with type declarations.
- Auto-pagination. List methods return an object you can
awaitfor one page or iterate for every item. - Retries on rate limits, 5xx responses and network failures, with
Retry-Aftersupport. - Automatic idempotency keys on every POST.
- Webhook verification for the
TrackSERPs-Signatureheader. - Exported types for requests, responses and webhook events.
It is for servers, scripts and serverless functions. It imports node:crypto, and the API sends no CORS headers, so a browser cannot call it with a key. Using Python instead? The Python client page has the equivalent code.
Install and create a client
npm install @trackserps/sdk
# or: pnpm add @trackserps/sdk
# or: yarn add @trackserps/sdk
import { TrackSERPs } from "@trackserps/sdk";
const client = new TrackSERPs({
apiKey: process.env.TRACKSERPS_API_KEY!, // ts_test_... while you build
maxRetries: 3, // default
timeoutMs: 30_000, // default
});
const account = await client.account.get();
const usage = await client.account.usage();
console.log(`${account.name} on ${account.plan}`);
console.log(`${usage.credits.monthly_remaining} of ${usage.credits.monthly_allowance} credits left`);
console.log(`${usage.api.rate_limit_per_minute} requests per minute per key`);
Create keys under the API keys page of the app. Use a ts_test_ key while building: it reads a synthetic demo project, never runs a real check and never spends credits, and write calls are validated without being saved. The client constructor throws if apiKey is empty.
Client options
| Option | Default | Meaning |
|---|---|---|
apiKey | required | ts_live_... or ts_test_..., sent as Authorization: Bearer |
baseUrl | https://api.trackserps.com/v1 | Trailing slashes are stripped |
maxRetries | 3 | Retries on rate limits, 5xx and network errors |
timeoutMs | 30000 | Per-request timeout |
fetch | global fetch | Custom implementation, handy in tests |
Every method also takes a trailing RequestOptions object: signal to cancel, headers to merge in, and idempotencyKey to override the generated one.
Every resource and method
The client exposes eleven resources. client.projects.keywords and client.projects.competitors are the same objects as client.keywords and client.competitors. Methods marked 0.3.0 need that version or later; methods marked 0.2.0 need at least that; the rest predate both.
| Resource | Methods | Notes |
|---|---|---|
account | get(), usage() | Plan, timezone, credit balances, API call allowance and per-minute limit |
projects | list(params?), get(id), create(body) (0.2.0), update(id, body) (0.3.0), shareOfVoice(id, params?) (0.3.0) | list is paginated; engine is fixed at creation, and update rejects a change with 422 engine_immutable |
locations | list({ q, country, engine, limit }) | Search for location_code values; engine is 0.3.0 |
keywords | list(projectId, params?), create(projectId, { keywords }) (0.3.0), delete(projectId, keywordId) (0.3.0), serp(projectId, keywordId, params?) (0.3.0), serpCompare(projectId, keywordId, { from, to }) (0.3.0) | create upserts up to 500 keywords; delete archives |
rankings | latest(projectId, params?), keywordLatest(projectId, keywordId, params?), keywordHistory(projectId, keywordId, params?), history(projectId, params?) | latest and history are paginated; include: "competitors" attaches competitor ranks |
volume | get(projectId, keywordId, { months }), list(projectId, params?) | Monthly volume, CPC and competition; list is paginated |
runs | trigger(projectId, params?) (alias create), latest(projectId), get(projectId, runId) | trigger takes dry_run, keyword_ids and fresh; no waitFor |
lookups | create({ items, fresh? }), get(id), list(params?), waitFor(id, options?) (all 0.2.0) | One-off checks without a project; 1 to 100 items per request |
competitors | list, add (alias create), remove (alias delete), shareOfVoice (all 0.3.0) | Competitor ranks come from SERPs already fetched, so adding one costs no credits |
share | get(projectId), update(projectId, { enabled, password?, regenerate? }) | Public read-only share link |
webhooks | list, create, get, update, delete, rotateSecret, test, deliveries | deliveries is paginated; every webhook method, reads included, needs webhooks:write |
Write methods need a key with the matching scope: keywords:write, runs:write, shares:write or webhooks:write, plus projects:write for project and competitor changes. A missing scope throws a TrackSERPsError with code forbidden_scope.
Async iterators and pagination
Every paginated method returns an AutoPagingPromise. It is both a promise for the first page and an async iterable over every item, so one method covers four patterns.
import { TrackSERPs, type LatestRanking } from "@trackserps/sdk";
const client = new TrackSERPs({ apiKey: process.env.TRACKSERPS_API_KEY! });
// 1. Await: first page only, typed as ProjectListResponse
const firstPage = await client.projects.list({ limit: 20 });
console.log(firstPage.projects.length, firstPage.next_cursor);
// 2. for await: every item across every page
for await (const project of client.projects.list({ limit: 100 })) {
console.log(project.id, project.name, project.keywords_count);
}
// 3. pages(): whole responses, useful for bulk history summaries
for await (const page of client.rankings.history("cmwc0f1yp0005rqk7w1plnab1").pages()) {
console.log(page.summary.improved, page.summary.declined);
}
// 4. all(): collect into an array (loads everything into memory)
const drops: LatestRanking[] = [];
for await (const r of client.rankings.latest("cmwc0f1yp0005rqk7w1plnab1", { device: "mobile", limit: 500 })) {
if (r.change_7d !== null && r.change_7d <= -3) drops.push(r);
}
const projects = await client.projects.list().all();
console.log(drops.length, projects.length);
Notes that save debugging time:
limitdefaults to 50 and goes up to 500. Use 500 when iterating whole lists; fewer round trips matter more than page size.- The cursor is opaque. Do not construct or store it across API versions.
- Awaiting and then iterating the same object reuses the first page it already fetched.
rankings.historyyields keyword objects with aseriesand adelta. The bulk endpoint counts as five requests toward your rate limit and monthly quota, so preferkeywordHistoryfor one keyword.rankisnullwhen the keyword was checked and the domain is not in the top 100. It is never0, andchange_7dis positive when you improved.
Create a project, add keywords and run a check
Reads cost no credits. Runs do: one credit per phrase per device. A dry run tells you the cost first. Checks normally take 10 to 20 minutes, even for one keyword, unless the same search was already fetched earlier the same UTC day. fresh: true skips that cache.
import { TrackSERPs, type Run } from "@trackserps/sdk";
const client = new TrackSERPs({ apiKey: process.env.TRACKSERPS_API_KEY! });
const FINAL: Run["status"][] = ["completed", "partial", "failed", "paused_no_credits"];
// client.runs has no waitFor: poll runs.get yourself.
async function waitForRun(projectId: string, runId: string, intervalMs = 60_000, timeoutMs = 30 * 60_000) {
const deadline = Date.now() + timeoutMs;
while (true) {
const run = await client.runs.get(projectId, runId);
if (FINAL.includes(run.status)) return run;
if (Date.now() + intervalMs > deadline) throw new Error(`run ${runId} still ${run.status}`);
await new Promise((resolve) => setTimeout(resolve, intervalMs));
}
}
const project = await client.projects.create({
name: "Acme Plumbing",
domain: "acmeplumbing.com",
folder_name: "Acme", // or folder_id; exactly one is required
location_code: 2840, // from client.locations.list({ q: "United States" })
devices: ["desktop", "mobile"],
schedule: "weekly",
keywords: ["emergency plumber", "drain cleaning"],
});
const added = await client.keywords.create(project.id, {
keywords: [
{
phrase: "water heater repair",
tags: ["services"],
tracked_urls: [{ url: "https://acmeplumbing.com/water-heaters", match: "exact" }],
},
],
});
const keywordId = added.results[0]!.keyword.id;
const estimate = await client.runs.trigger(project.id, { dry_run: true });
if (!estimate.allowed) throw new Error(`run not allowed: ${estimate.reason}`);
const run = await client.runs.trigger(project.id, { keyword_ids: [keywordId], fresh: true });
console.log(`queued ${run.run_id}, holding ${run.credits_held} credits`);
const finished = await waitForRun(project.id, run.run_id);
console.log(finished.status, finished.keywords_checked, finished.credits_charged);
What matters here:
- Runs have no
waitFor. The helper above pollsruns.getonce a minute. Final statuses arecompleted,partial,failedandpaused_no_credits. - Overloads follow
dry_run. Passing{ dry_run: true }types the result asRunDryRunResponse(would_hold,balance_after,allowed,reason). Anything else types it asRunCreateResponse. - Cooldown. One manual run per project every 10 minutes, at most 10 run requests per key per hour. Too soon gives
429 run_too_soon, which the SDK throws as aRateLimitErrorwithout retrying. - Targeted runs (
keyword_ids, up to 500) update only those keywords and do not appear inruns.latestorlast_run_at. - Project creation does not start a run. Scheduled runs pick the project up, or call
runs.trigger.
One-off lookups and waitFor
Lookups answer "where does this domain rank for this phrase?" without adding a tracked keyword. Each item holds one credit up front, a batch holds 1 to 100 items, results are kept for 30 days, and failed lookups are refunded.
import { TrackSERPs } from "@trackserps/sdk";
const client = new TrackSERPs({ apiKey: process.env.TRACKSERPS_API_KEY! });
const { data } = await client.lookups.create({
items: [
{ phrase: "commercial plumber", domain: "acmeplumbing.com", location_code: 2840, device: "desktop" },
{ phrase: "emergency plumber", domain: "acmeplumbing.com", location_code: 2840, url: "https://acmeplumbing.com/emergency", match: "exact" },
],
});
for (const item of data) {
// Cached same-day results arrive already completed; the rest are queued.
const lookup = item.status === "completed" ? item : await client.lookups.waitFor(item.id);
if (lookup.status === "failed") {
console.error(`${lookup.phrase}: ${lookup.error}`);
continue;
}
console.log(`${lookup.phrase}: rank ${lookup.result?.rank ?? "not in top 100"}, cached ${lookup.result?.cached}`);
}
for await (const lookup of client.lookups.list({ status: "completed", created_after: "2026-11-01T00:00:00Z" })) {
console.log(lookup.id, lookup.result?.rank);
}
waitFor polls get until the status is completed or failed. The interval defaults to 60,000 ms and is clamped to a minimum of 15,000 ms; the timeout defaults to 1,800,000 ms (30 minutes). A failed lookup is returned, not thrown, so check status. A timeout, or a signal aborted between polls, rejects with a plain Error, not a TrackSERPsError; an abort that lands mid-request surfaces as a TrackSERPsError with code network_error. If you submit 100 items, waitFor in a loop makes 100 polling chains; a lookup.completed webhook is cheaper.
Errors, retries and rate limits
Every non-2xx response throws. TrackSERPsError carries code, status, requestId, fields, details (the parsed body) and retryAfter. RateLimitError extends it and is thrown for every 429.
import { TrackSERPs, TrackSERPsError, RateLimitError } from "@trackserps/sdk";
const client = new TrackSERPs({ apiKey: process.env.TRACKSERPS_API_KEY! });
try {
await client.runs.trigger("cmwc0f1yp0005rqk7w1plnab1", { fresh: true });
} catch (err) {
if (err instanceof RateLimitError) {
// Any 429 that survived the SDK's own retries: rate_limited, run_too_soon or quota_exceeded
console.warn(`${err.code}: retry in ${err.retryAfter ?? "?"}s (request ${err.requestId})`);
} else if (err instanceof TrackSERPsError) {
console.error(err.status, err.code, err.message, err.fields, err.requestId);
if (err.code === "insufficient_credits") {
console.error(err.details); // parsed body: { error: { needed, available, ... } }
}
} else {
throw err; // not an API error
}
}
What the SDK retries, exactly:
| Situation | Retried? | Wait |
|---|---|---|
429 with code rate_limited | Yes | Retry-After seconds if 30 or less, otherwise exponential backoff (500 ms, 1 s, 2 s plus up to 200 ms jitter) |
429 with run_too_soon or quota_exceeded | No | Thrown immediately with retryAfter set |
| 5xx | Yes | Same rule as above |
| Network error or timeout | Yes | 500 ms, 1 s, 2 s |
| 4xx other than 429 | No | Thrown immediately |
Total waiting across retries is capped at 30 seconds, and after maxRetries the last error is thrown. Two consequences: a Retry-After longer than 30 seconds is not waited out, and an IP lockout after repeated failed authentication (a 300-second Retry-After) surfaces quickly as an error. If a client of yours should sleep 10 minutes on run_too_soon, do that in your own code using err.retryAfter.
A failure that never reached the server throws TrackSERPsError with code network_error and status 0. The SDK also fills in unauthorized, forbidden_scope, not_found, rate_limited or api_error when a response has no error body.
Idempotency
Every POST gets a UUID Idempotency-Key automatically, and it is reused across the SDK's internal retries. A timeout that hid a successful response therefore replays the original result rather than repeating the work. Supply your own key when your job might be re-run: { idempotencyKey: "nightly-2026-11-11" }. Reusing a key with a different body returns 409 idempotency_mismatch. Pass idempotencyKey: null to send none.
Verify webhooks
verifyWebhook(rawBody, header, secret, options?) returns a boolean. It parses t=<unix>,v1=<hex>, rejects timestamps more than toleranceSeconds (300 by default) from now, recomputes the HMAC-SHA256 of the timestamp, a dot and the raw body, and compares with a constant-time check. Pass an array of secrets during a rotation, when the header carries two v1 values.
// app/api/trackserps/route.ts (Next.js App Router)
import { verifyWebhook, type WebhookEventRankingsUpdated } from "@trackserps/sdk";
const secrets = [
process.env.TRACKSERPS_WEBHOOK_SECRET,
process.env.TRACKSERPS_WEBHOOK_PREVIOUS_SECRET, // only during a rotation
].filter((s): s is string => Boolean(s));
export async function POST(request: Request) {
const rawBody = await request.text(); // raw string: never re-serialise parsed JSON
const header = request.headers.get("trackserps-signature") ?? "";
if (!verifyWebhook(rawBody, header, secrets)) {
return new Response("invalid signature", { status: 400 });
}
const event = JSON.parse(rawBody) as { id: string; type: string };
if (event.type === "rankings.updated") {
const { data } = event as WebhookEventRankingsUpdated;
for (const c of data.changes) console.log(`${c.phrase} [${c.device}]: ${c.previous_rank} -> ${c.rank}`);
}
return new Response(null, { status: 200 });
}
Rules that apply to every receiver: verify against the raw body before parsing, answer within 10 seconds, and expect repeats. Failed deliveries are retried (8 attempts in total) and the event id is stable across attempts, so deduplicate on it. After 20 consecutive failures the endpoint is disabled. lookup.completed fires for failed lookups too, and its data is the full lookup object. See the webhooks reference for every event and the guide on alerting on ranking drops.
History, SERP snapshots and share of voice
These need 0.3.0 for the competitor and snapshot methods, and they read data TrackSERPs already stored, so they cost no credits.
import { TrackSERPs } from "@trackserps/sdk";
const client = new TrackSERPs({ apiKey: process.env.TRACKSERPS_API_KEY! });
const projectId = "cmwc0f1yp0005rqk7w1plnab1";
// Bulk history: counts as 5 requests toward the rate limit and monthly quota
const history = await client.rankings.history(projectId, { start: "2026-10-01", end: "2026-11-01", unranked_as: 101 });
console.log(history.summary.average_rank_change, history.summary_total.keywords);
// What changed in the top 100 for one keyword between two checked dates
const diff = await client.keywords.serpCompare(projectId, "cmwc0f2ab0007rqk7x9kd3m2p", { from: "2026-10-01", to: "2026-11-01" });
console.log(diff);
// Share of voice for the project domain and every tracked competitor
await client.competitors.add(projectId, { domain: "rival.example", label: "Rival" });
const sov = await client.projects.shareOfVoice(projectId, { weighted: "volume" });
for (const d of sov.domains) console.log(d.domain, d.current_sov);
TypeScript types
The package re-exports the generated paths, operations and components types, and named aliases for the common shapes: Project, Keyword, LatestRanking, Run, Lookup, LookupResult, Competitor, ShareOfVoiceResponse, WebhookEndpoint, WebhookEventRankingsUpdated, WebhookEventLookupCompleted and more. Use them for your own function signatures:
import type { LatestRanking, Run, Lookup } from "@trackserps/sdk";
type Drop = Pick<LatestRanking, "phrase" | "device" | "rank" | "change_7d">;
const isFinal = (r: Run) => ["completed", "partial", "failed", "paused_no_credits"].includes(r.status);
const rankOf = (l: Lookup) => l.result?.rank ?? null;
Because rank, change_7d and result are nullable in the spec, strict mode makes you handle "not ranked" and "not finished yet" explicitly.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
client.competitors or keywords.serp is undefined | Installed version older than 0.3.0 | Upgrade to 0.3.0 or later |
TrackSERPsError: forbidden_scope | Key lacks the scope for a write | Create a key with the scope; write scopes need a plan with write access |
RateLimitError with run_too_soon | Second manual run within 10 minutes | Wait err.retryAfter seconds, or read existing results |
waitFor rejects with "did not finish" | Timeout shorter than the 10 to 20 minute queue time | Raise timeoutMs, or use a webhook |
verifyWebhook returns false | Body was parsed and re-serialised, wrong secret, clock skew over 5 minutes | Use the raw body and the full whsec_ string; sync the clock |
validation_error with fields | Unknown field, bad enum, out-of-range value | Read err.fields; the types usually catch it first |
Works locally, network_error in CI | No outbound network access from the runner | Allow api.trackserps.com over HTTPS, or pass a custom fetch your network requires |
When the SDK is the wrong tool
Not in TypeScript: use the Python client or call the REST API directly. Exploring endpoints by hand: the Postman collection is faster. Want an AI assistant to query rankings in conversation: use the MCP server. For a first call, follow the API quickstart with a test key.
Frequently asked questions
How do I install the TrackSERPs Node.js SDK?
Can I use @trackserps/sdk in the browser?
Does the SDK retry failed requests?
How do I wait for a check to finish with the SDK?
What does verifyWebhook return?
How do I cancel or time out a request?
Can I test code that uses the SDK without spending credits?
Sources & references
- Node.js documentation: Globals, fetch(checked 2026-11-11)