takt

Read SDK

@vskstudio/takt-read is a server-only TypeScript SDK over the HTTP Read API. It wraps the Bearer-authenticated /api/v1/sites/{domain}/stats/* endpoints in typed methods, so you can pull your analytics into a backend, a cron job or an API route without writing HTTP by hand.

pnpm add @vskstudio/takt-read

It has zero runtime dependencies, ships ESM + CJS, and needs Node.js ≥ 20 (native fetch).

Your read API key is a secret. Use this SDK server-side only. Never ship it in a browser bundle.
This SDK stays read-only, by design: it will not create goals, sites or invitations. To write (sites, goals, funnels, segments, alerts, members), use the remote MCP server, authorized through OAuth and bounded by your role.

Quick start

import TaktClient from '@vskstudio/takt-read'

const takt = new TaktClient({
  apiKey: process.env.TAKT_API_KEY!, // secret: keep it server-side
  domain: 'example.com',
  org: 'my-org', // optional, only needed by stats.export() and stats.exportResult()
  timeoutMs: 30_000, // optional, default 30s
  retries: 2 // optional, default 2 (retries 429 + 5xx with backoff)
})

const summary = await takt.stats.summary({ period: '30d' })
console.log(summary.visitors, summary.pageviews)

baseUrl is optional: it defaults to the hosted Read API root (https://taktlytics.com/api/v1). Set it to target another host (a first-party proxy, a test environment) and keep the /api/v1 prefix, e.g. https://proxy.example.com/api/v1. Plain http:// is accepted only on the loopback interface (localhost, 127.0.0.1, [::1]); any other host must use https://. The constructor validates its options and throws a TaktError (code: 'config_invalide') on bad input.

TaktClient options:

OptionTypeDefaultRole
apiKeystringnoneAPI key with the stats:read permission
domainstringnoneSite to query (bound to the key)
orgstringnoneOrg slug owning domain; only needed by stats.export() and stats.exportResult()
baseUrlstringhttps://taktlytics.com/api/v1Root of the Read API (…/api/v1)
fetchtypeof fetchglobal fetchCustom fetch implementation
timeoutMsnumber30000Per-request timeout
retriesnumber2Retries on 429/5xx/network with backoff

Stats methods

All read endpoints live under takt.stats. Every method takes an optional final { signal } argument for cancellation via an AbortController.

MethodReturns
stats.summary(query?)StatsSummary
stats.timeseries(query?)StatsTimeseries
stats.breakdown(query & { dimension })StatsBreakdown
stats.breakdowns(dimensions, query?)StatsBreakdowns
stats.realtime()StatsRealtime
stats.goals(query?)StatsGoals
stats.funnels(query?)FunnelReports
stats.properties(event, query?)string[]
stats.propertyBreakdown(event, key, query?)PropertyBreakdown
stats.propertyBreakdownBatch(request, query?)PropertyBatchResponse
stats.revenue(event, query?)RevenueByCurrency
stats.export(query?)string (CSV) or StatsExportRow[] (JSON)
stats.exportResult(query?)StatsExportResult<string> (CSV) or StatsExportResult<StatsExportRow[]> (JSON)
const ac = new AbortController()
const realtime = await takt.stats.realtime({ signal: ac.signal })

// Several rankings in one request
const { breakdowns } = await takt.stats.breakdowns(['pages', 'sources'], { period: '30d' })

// Page ranking export (needs `org` on the client)
const csv = await takt.stats.export({ period: '30d' }) // raw CSV string
const rows = await takt.stats.export({ period: '30d', format: 'json' }) // StatsExportRow[]

The export is capped server-side at 999 rows and 256 KB, in CSV as in JSON. When the cap cuts rows off, the API sets the X-Takt-Truncated: true header and the body stays a plain CSV string or JSON array. stats.export() returns that body as is. stats.exportResult(), available since takt-read 0.6.0, returns { data, truncated } so you know whether rows are missing:

const { data, truncated } = await takt.stats.exportResult({ period: '30d', format: 'json' })
if (truncated) {
  // data holds the first rows only: narrow the period or segment to get the rest
}

truncated is false when the header is false or absent. data has the same type as the stats.export() result for the same format.

Query options

Read methods accept an optional StatsQuery: a period (day, 7d, 30d, month, 6mo, 12mo) or an explicit from/to range, plus tz, country, interval, compare, limit and segment filters.

await takt.stats.timeseries({
  period: '30d',
  interval: 'day',
  tz: 'Europe/Paris',
  compare: true, // include the previous period
  segment: [
    { dim: 'browsers', op: 'is', val: 'Firefox' },
    { dim: 'pages', op: 'not', val: '/blog', join: 'or' }
  ]
})

dimension and segment[].dim take a StatsDimension: pages, sources, countries, regions, cities, os, browsers, devices, utm_source, utm_medium, utm_campaign (plural: page or source are not valid). segment[].op is is or not.

Error handling

Non-2xx responses throw a TaktError carrying the HTTP status and the API’s error code. The SDK also raises config_invalide on bad options, timeout when a request exceeds timeoutMs, and erreur_reseau on network failure.

import { TaktError } from '@vskstudio/takt-read'

try {
  await takt.stats.summary()
} catch (err) {
  if (err instanceof TaktError && err.code === 'trop_de_requetes') {
    await new Promise((resolve) => setTimeout(resolve, 10_000))
  }
}
The SDK consumes the same Read API as direct HTTP calls, included with no volume limit. Past 200 requests per 10 seconds or 600 per minute for a single key, the endpoints return 429 (trop_de_requetes): wait for the delay in the Retry-After header before retrying. Upstream, the gateway also caps each IP address at 20 requests per second (bursts of up to 100): that 429 has an HTML body and no Retry-After, so wait one second. Ingestion is never affected. Prefer natural language? See the MCP server.