@rustrak/client is the official TypeScript client for the Rustrak REST API. It is generated from the server’s OpenAPI spec, so it has one method for every endpoint the server documents, validates requests and responses with Zod, retries transient failures, and returns a Result that never throws for an expected failure. HTTP is the platform’s fetch; the only runtime dependency is Zod.
Every method returns a Result<T, RustrakError>: a plain object that is either { success: true, data } or { success: false, error }. Check success before reading data, and TypeScript narrows the rest.
There are no error classes. Every failure is one member of a single closed union, discriminated by kind:
import { isRetryable, type RustrakError } from '@rustrak/client';const result = await client.projects.list();if (!result.success) { switch (result.error.kind) { case 'unauthenticated': redirect('/login'); // ONLY this kind means "log in again" break; case 'rate_limited': wait(result.error.retryAfter ?? 30); break; case 'network': // Branch on `reason`, not on `message`: the message is a fixed string by // design, because the underlying one names the host and port. console.log(result.error.reason); // 'timeout' | 'unreachable' break; default: if (isRetryable(result.error)) scheduleRetry(); }}
TypeScript
kind
HTTP
Retryable
Description
validation
400
❌
The server rejected the request
unauthenticated
401
❌
No session, or an invalid/expired token
forbidden
403
❌
Authenticated, but not allowed
not_found
404
❌
The resource does not exist
conflict
409
❌
Uniqueness violation: a taken name or slug
gone
410
❌
The resource was retired
payload_too_large
413
❌
Envelope ingestion only
rate_limited
429
✅
Rate limit exceeded; carries retryAfter?: number
client_error
other < 500
408 only
Any sub-500 status no other member claims
server_error
500+
500, 502, 503, 504
Any 5xx; the server’s own message is discarded
invalid_request
n/a
❌
Your input failed a pre-flight check; never sent
network
n/a
✅
DNS, connection refused, TLS, timeout, abort
invalid_response
n/a
❌
A 2xx arrived with a body the schema rejects
The union is closed, so a switch on kind with a default covers every case that exists. status is a plain number rather than a literal union, so a proxy-generated 502 or a future status is a value you can log rather than a type error.
A 4xx that blamed specific inputs carries fields, so a form can mark the input the server rejected instead of showing a toast the user has to translate back into an edit:
const created = await client.projects.create({ body: { name: 'My App' } });if (!created.success && created.error.kind === 'conflict') { for (const field of created.error.fields ?? []) { console.log(field.field, field.code); // e.g. 'slug' 'already_exists' }}
TypeScript
field is a dot path into the request body (slug, credentials.webhook_url), which is exactly what a form library’s setError takes. Pick the copy you show from (field, code) rather than from message; that is what makes it translatable. message is populated only for code: 'custom', where the code set genuinely cannot express the reason.
One rule when wiring this to a form: only call setError for names your form actually registers. A path naming an input the form does not have registers a phantom field that nothing can ever clear, and the form then refuses to submit with nothing on screen explaining why. Route the rest to a form-level error.
import { unwrap, unwrapOr, mapResult } from '@rustrak/client';
TypeScript
unwrap throws on a failure: the caller explicitly opting back into exceptions. unwrapOr substitutes a fallback.
Do not reach for unwrapOr to make a page compile.unwrapOr(await client.projects.list(), []) renders the same empty state for “this account has no projects” and “the server is unreachable”, which is exactly the regression this API exists to prevent. It is appropriate only where the fallback is genuinely correct regardless of why the call failed: a cached-count optimisation, a best-effort telemetry read, a script that already logged the error.
These examples are for your own Next.js application calling a Rustrak server
through the client. RUSTRAK_API_URL and RUSTRAK_API_TOKEN are your app’s
settings: the server’s address and an API token.
A Result is a plain object with no prototype chain, so it survives structuredClone and therefore React’s server/client boundary. A thrown error class does not: it reaches the browser as an opaque digest, which is why returning the failure is the recommended shape.
'use server';import { RustrakClient } from '@rustrak/client';export async function resolveIssue(projectId: number, issueId: string) { const client = new RustrakClient({ baseUrl: process.env.RUSTRAK_API_URL!, token: process.env.RUSTRAK_API_TOKEN!, }); // Returned as-is: the calling component gets the actual failure rather than // an "An error occurred in the Server Components render" digest. return client.issues.update({ path: { project_id: projectId, issue_id: issueId }, body: { status: 'resolved' }, });}
'use client';import useSWR from 'swr';export function IssuesList({ projectId }: { projectId: number }) { // The fetcher never rejects, so SWR's `error` stays empty: the failure is in // `data`. Unwrap it in the fetcher if you want SWR's retry behaviour. const { data } = useSWR(['issues', projectId], () => client.issues.list({ path: { project_id: projectId } }), ); if (!data) return <Spinner />; if (!data.success) return <LoadFailed error={data.error} />; return <List items={data.data.items} />;}
Every request and response type in the spec is exported under the name the spec
gives it:
import type { ProjectResponse, IssueResponse, EventDetailResponse, IssuesListData, // what client.issues.list takes IssuesListResponse, // what it returns on success // the Result API Result, RustrakError, RustrakErrorKind, FieldError, FieldErrorCode,} from '@rustrak/client';
TypeScript
Value exports for the same API: Ok, Err, unwrap, unwrapOr, mapResult, isRetryable, FIELD_ERROR_CODES, SERVER_ERROR_MESSAGE, NETWORK_ERROR_MESSAGE, TIMEOUT_ERROR_MESSAGE.
One issue with its releases and its 24h and 30d series (Sentry’s GroupDetailsEndpoint).
sentry.getLatestEvent({ path })
GET /api/0/issues/{issue_id}/events/latest/
The issue’s most recent event (Sentry’s GroupEventDetailsEndpoint, issues/endpoints/group_event_details.py).
sentry.listIssues({ path, query? })
GET /api/0/projects/{org_slug}/{project_slug}/issues/
Issues, filtered by query, sorted by sort and paginated by cursor (Sentry’s ProjectGroupIndexEndpoint, issues/endpoints/project_group_index.py).
sentry.listOrganizationIssues({ path, query? })
GET /api/0/organizations/{org_slug}/issues/
Issues across projects, narrowed by project, filtered by query, sorted by sort and paginated by cursor (Sentry’s OrganizationGroupIndexEndpoint, issues/endpoints/organization_group_index.py).
sentry.listOrganizations()
GET /api/0/organizations/
The organizations the token belongs to (Sentry’s OrganizationIndexEndpoint): always the one synthetic org.
sentry.listProjects({ query? })
GET /api/0/projects/
The projects the token can see, newest first (Sentry’s ProjectIndexEndpoint, core/endpoints/project_index.py).
sentry.listRepos({ path })
GET /api/0/organizations/{org_slug}/repos/
The code repositories connected to the organization (Sentry’s OrganizationRepositoriesEndpoint).
sentry.openIssue({ path })
GET /{org_slug}/{project_slug}/issues/{issue_id}
The issue page GitLab’s “View in Sentry” opens: Sentry redirects this legacy path to the issue (static/app/router/routes.tsx), Rustrak to its dashboard.
sentry.submitUserFeedback({ path, body })
POST /api/0/projects/{org_slug}/{project_slug}/user-feedback/
Submit a user report about an error event (Sentry’s ProjectUserReportsEndpoint, feedback/endpoints/project_user_reports.py).
sentry.updateIssue({ path, body })
PUT /api/0/issues/{issue_id}/
Sets an issue’s status and returns the issue (Sentry’s GroupDetailsEndpoint.put).
Returns one span together with its attributes and tags — the gen_ai.* payload (prompts, responses, tool arguments and results) that the list response deliberately omits, since spans.data is untrimmed and a whole trace’s worth of it would dwarf the waterfall it is drawn from.
spans.list({ path, query? })
GET /api/projects/{project_id}/spans
Lists spans for a project with offset-based pagination (newest by start_timestamp first), optionally filtered by op/status/trace_id, over a window of 90 days at most (every span of a trace when only trace_id is given).
Gives the space deleted data held back to the disk: on SQLite it rewrites a file created before incremental mode, on Postgres it rewrites each table retention deletes from (VACUUM FULL), locking that table while it does.
storage.executeCleanup({ body })
POST /api/storage/cleanup
Starts deleting old data and the issues it empties.
storage.gcSourceMaps()
POST /api/storage/source-maps/gc
Delete orphaned source maps (DB + disk).
storage.getAge()
GET /api/storage/age
Rows per age bucket, per project and kind.
storage.getCleanupStatus()
GET /api/storage/cleanup/status
Progress of the running cleanup, or the outcome of the last one.
storage.getCompaction()
GET /api/storage/compaction
Whether the database file shrinks when data is deleted, and the disk a one-off compaction needs.
storage.getPlugins()
GET /api/storage/plugins
Lists each installed plugin’s data: its file, its quota, and its history (the tables with created_at) against its retention.
storage.getProjects()
GET /api/storage/projects
Per-project counts and estimated weight.
storage.getRetention()
GET /api/storage/retention
Gets the retention settings and the cleanup schedule.
storage.getSummary()
GET /api/storage/summary
Row counts, DB size, and source-map weight.
storage.previewCleanup({ body })
POST /api/storage/cleanup/preview
Dry-run count, mutates nothing.
storage.previewRetention({ body })
POST /api/storage/retention/preview
What saving these settings would delete on the next cleanup, without saving or deleting anything.
storage.previewSourceMapGc()
POST /api/storage/source-maps/gc/preview
Dry-run orphan count, deletes nothing.
storage.runRetention()
POST /api/storage/retention/run
Enforces the saved retention now, without waiting for the schedule.
storage.updateRetention({ body })
PUT /api/storage/retention
Updates the retention settings; the next cleanup is scheduled at once.
GET /api/projects/{project_id}/transactions/{transaction_id}
Returns a single transaction with its full Sentry payload (spans, contexts, measurements, tags) for the performance detail view.
transactions.getOverview({ path, query? })
GET /api/projects/{project_id}/transactions/overview
Returns how the project is doing over a window: calls, failure rate, p50 and p95 against the window of the same length just before it, and the window’s trend bucket by bucket.
transactions.getQuery({ path, query? })
GET /api/projects/{project_id}/transactions/queries/{group}
Returns one query shape over a window: how often it ran, its average and p95, its trend, the endpoints and jobs it runs in and its slowest calls.
transactions.getSpans({ path })
GET /api/projects/{project_id}/transactions/{transaction_id}/spans
Returns the indexed spans extracted from a transaction, ordered for the waterfall view (by start_timestamp ascending).
transactions.getStatGroup({ path, query })
GET /api/projects/{project_id}/transactions/stats/group
Returns the aggregate stats for a single transaction group — a direct lookup so the summary header works regardless of how many groups the project has.
GET /api/projects/{project_id}/transactions/stats/group/breakdown
Returns where one endpoint’s time goes, averaged per call over its latest calls in the window: database, outgoing HTTP, cache, templates and the app’s own code.
GET /api/projects/{project_id}/transactions/stats/group/timeseries
Returns one endpoint’s trend over the window, every bucket present: how often it ran and failed, and its p50 and p95.
transactions.getStats({ path, query? })
GET /api/projects/{project_id}/transactions/stats
Returns paginated aggregate performance stats (count, time spent, p50/p95/p99 latency, failure rate) grouped by transaction name + op, the most time spent first unless sort asks otherwise.
transactions.list({ path, query? })
GET /api/projects/{project_id}/transactions
Lists transactions for a project with offset-based pagination (newest or slowest first), over a window of 90 days at most.
transactions.listQueries({ path, query? })
GET /api/projects/{project_id}/transactions/queries
Lists the database queries of a window grouped by their shape (values, comments and layout taken out), the most time spent in the database first, with how often each ran, its average, its slowest run and its share of that time.
GET /api/projects/{project_id}/web-vitals/breakdown
Returns one vital on each device or on each browser: where it is good and where it is not, the most measured first.
webVitals.getSummary({ path, query? })
GET /api/projects/{project_id}/web-vitals
Returns the project’s performance score over the window, or one page’s, with each vital’s 75th percentile and the spread around it, average score and how many of its measurements rate good, needing improvement and poor.
webVitals.getTimeseries({ path, query? })
GET /api/projects/{project_id}/web-vitals/timeseries
Returns how the window’s measurements rate bucket by bucket, every bucket present: how many were good, needed improvement and were poor.
webVitals.listPages({ path, query? })
GET /api/projects/{project_id}/web-vitals/pages
Returns the pages with web vitals in the window, the one whose improvement would raise the project’s score the most first, or its score for one vital when vital names it.
webVitals.listSamples({ path, query? })
GET /api/projects/{project_id}/web-vitals/samples
Returns the window’s worst measurements, ten at most, with where each happened: the page and its URL, the element, the browser, the device, the network and the page load’s transaction.
webVitals.listTargets({ path, query? })
GET /api/projects/{project_id}/web-vitals/targets
Returns what the window’s vitals were about: an LCP’s element and the resource it loaded, a layout shift’s element, an interaction’s target.