Reference docs: https://apet97.github.io/clockify-ts-sdk/
On the npm page, this README's relative links do not resolve. Use these absolute pointers:
TypeScript SDK for the Clockify REST API. It covers
all 175 operations of the API as client.<resource>.<verb>() methods in 33
resource modules, with typed requests and responses, and works from ESM and
CommonJS.
Requires Node.js >=22.13.0.
createClockifyClient() — single-import factory, env-var
fallback (CLOCKIFY_API_KEY / CLOCKIFY_ADDON_TOKEN), no
user-visible workaround castsclockifyDiagnostics() — no-network readiness receipt for auth,
runtime, workspace ID, base URL overrides, warnings, and next stepsiterAll + page-envelope iterPages;
iterPages consumes the Last-Page response header where the
server emits itClockify-Signature header), a typed
receiver for Fetch and Node servers, signed test deliveries, and a reader
for deliveries Clockify could not completeUser-Agent + X-Request-Id auto-injection,
lifecycle hooks (beforeRequest / afterResponse / onError
/ onRetry), configurable retry policy (Retry-After and
X-RateLimit-Reset aware)See the MCP host compatibility guide for client setup and Reports App support.
npm install @apet97/clockify115-sdk
This is an unofficial, community-built package (not affiliated with
CAKE.com or Clockify); the -115 suffix is deliberate trademark distance.
Node.js >= 22.13 and Cloudflare Workers are tested runtimes. On Workers, enable the
nodejs_compat compatibility flag: the SDK imports node:crypto (timingSafeEqual,
randomUUID) and node:os (platform/arch for the default User-Agent), which
that flag provides.
import { createClockifyClient } from "@apet97/clockify115-sdk";
// Reads CLOCKIFY_API_KEY (or CLOCKIFY_ADDON_TOKEN) from env.
const client = createClockifyClient();
const tags = await client.tags.list({
workspaceId: process.env.CLOCKIFY_WORKSPACE_ID!,
});
for (const tag of tags) console.log(tag.id, tag.name);
createClockifyClient is the recommended entry. It accepts at
most one of apiKey or addonToken (or reads from env when both
are omitted), wraps fetch with composedFetch for
User-Agent + X-Request-Id injection, and routes through your
hooks / retry policy.
Clockify exposes two mutually-exclusive auth schemes:
| Scheme | Header | When to use |
|---|---|---|
| Personal API key | X-Api-Key |
Server scripts, CI, agents acting as you. Token at Clockify profile settings. |
| Marketplace addon token | X-Addon-Token |
Code running inside a Clockify addon you authored. Token from the install JWT. |
createClockifyClient enforces exactly-one at compile time and
runtime — the discriminated-union type rejects passing both:
const personal = createClockifyClient({ apiKey: "..." });
const addon = createClockifyClient({ addonToken: "..." });
// ❌ Compile error: both fields can't be set together.
const broken = createClockifyClient({ apiKey: "a", addonToken: "t" });
If you omit both, the factory reads from the environment:
| Env var | Used as | Precedence (priority) |
|---|---|---|
CLOCKIFY_API_KEY |
apiKey |
1 (highest) |
CLOCKIFY_ADDON_TOKEN |
addonToken |
2 |
Explicit options always win. Empty-string env values are treated as absent. Throws if both env vars are also unset.
const client = createClockifyClient(); // reads env
apiKey and addonToken accept any Supplier<string> — a
string, Promise<string>, or sync/async function. Use a function
for tokens that get rotated:
const client = createClockifyClient({
apiKey: () => fetchTokenFromVault(),
});
routing is a typed, validated way to select a per-service base URL from the
H02-ROUTING-approved profile set,
instead of the single blanket environment/baseUrl override (the two are
mutually exclusive — pass one or the other, never both — and an invalid
routing value throws synchronously, before the client is constructed).
routing is applied at request dispatch: the factory
resolves it into a sparse per-service base-URL map that the generated request
runtime consults per operation. Precedence is baseUrl > environment > the
routing service URL > the operation's own servers override > the default
host, so a custom profile naming only regular leaves reports/audit on
their own routes. Only the global profile is live-confirmed: every regional
and subdomain profile requires acknowledgeUnconfirmedRegion: true (and
custom requires allowCustomHttpsHosts: true), so treat non-global
routing as unproven for data residency until it is live-confirmed against a
real regional workspace.
The generated runtime's serviceBaseUrls map is intentionally not accepted by
createClockifyClient; use routing so host validation and regional
acknowledgement cannot be bypassed.
import { createClockifyClient, type ClockifyRoutingOptions } from "@apet97/clockify115-sdk/create-client";
const routing: ClockifyRoutingOptions = { profile: "global" };
const client = createClockifyClient({ routing }); // auth from env
A client sends its credential only over HTTPS and only to these hosts, so a changed environment variable or config file cannot redirect it:
api.clockify.me, reports.api.clockify.me, auditlog-api.api.clockify.me
and developer.clockify.me;euc1.clockify.me, use2.clockify.me,
euw2.clockify.me and apse2.clockify.me;Pass allowNonClockifyHttpsHost: true only for a proxy you trust with the
credential. Plain HTTP stays rejected.
timeoutInSeconds has no default: without it a request waits until the socket
gives up, because detailed reports and exports can run for minutes. Set it on
the client, or use withRequestTimeout(seconds) for one call, wherever your
recovery depends on a timeout.
Bypass the factory and construct ClockifyApiClient directly for
non-header auth (mock client, custom OAuth, addon-token-from-JWT):
import { ClockifyApiClient } from "@apet97/clockify115-sdk";
const client = new ClockifyApiClient({
apiKey: "...",
auth: false, // or a custom AuthProvider / function
});
createClockifyClient intentionally rejects its generated auth option: the
factory owns the top-level apiKey / addonToken pair and environment fallback,
so accepting a second provider there would make credential precedence ambiguous.
The generated client models apiKey and addonToken as mutually
exclusive. createClockifyClient remains the recommended entry because
it adds env fallback, request IDs, user-agent headers, hooks, and retry
configuration.
ClockifyApiClient.fetch() is the authenticated escape hatch for an endpoint
that is not yet represented by a generated method. Relative targets resolve
against the configured base path; absolute strings, URL values, and
Request inputs must have the same origin as that base. Base suppliers resolve
in baseUrl → environment → default order and are validated before
authentication. Non-loopback HTTP is always rejected, and a non-Clockify HTTPS
host requires allowNonClockifyHttpsHost: true.
const response = await client.fetch("workspaces/ws-id/example", {
method: "PUT",
body: JSON.stringify({ enabled: true }),
});
Input Request properties are preserved unless init overrides them. Header
precedence is input Request → client defaults → init → request options → SDK
authentication, so callers cannot replace the configured auth header. With
configured authentication disabled (auth: false), an add-on token can be
supplied in the raw call's request options. If a configured provider emits
X-Api-Key or X-Addon-Token, that scheme wins and the alternate Clockify
auth header is removed. The final merged headers are also checked, so manual
auth: false requests cannot carry both schemes. Query
overrides replace existing values; arrays become ordered repeated values and an
empty array removes the key. Signal precedence is request options → init →
input Request. Timeout precedence is request options → client options; retry
precedence is request options → client options → two retries. Because
fetch() returns the raw Response, timeoutInSeconds bounds only the wait
for response headers; the caller's abort signal keeps cancelling the body read
(response.text(), response.json(), the stream) after fetch() resolves.
Only GET, HEAD, and OPTIONS retry by default (RETRY-001; PUT/DELETE
require the explicit retryMutationMethods opt-in), for status 408, 429,
500, 502, 503, or 504. Retry and timeout controls are
validated before dispatch. Retryable bodies must be cloneable: the SDK builds
one finalized Request template, preflights replayability, and dispatches a
fresh clone for every attempt. Caller abort reasons are preserved, retryable
response bodies are cancelled before abort-aware backoff, and authenticated
requests never follow redirects (redirect: "follow" is rejected). A 3xx
answer is never retried: it surfaces once as RedirectNotAllowedError
(err.name === "RedirectNotAllowedError", with .status and .location).
Use clockifyDiagnostics() before constructing a client when you want a
local readiness receipt without contacting Clockify. It never returns raw
tokens; auth values are reported only as configured/redacted. Pair it with
client.health() for the first live credential probe.
import { clockifyDiagnostics, clockifyHealth, createClockifyClient } from "@apet97/clockify115-sdk";
const diagnostics = clockifyDiagnostics();
if (!diagnostics.ok) {
console.error(diagnostics.readiness, diagnostics.next);
process.exit(1);
}
const client = createClockifyClient();
const health = await clockifyHealth(client);
The diagnostics receipt includes checks, warnings, and next fields
for operator runbooks and support bundles. It checks CLOCKIFY_API_KEY,
CLOCKIFY_ADDON_TOKEN, CLOCKIFY_WORKSPACE_ID, Node.js 22.13+, and base URL
overrides without creating network traffic.
clockifyHealth(client) makes one current-user request. It checks connectivity
and authentication, measures latency, and reads the server Date header when
the header is available. The function does not throw. Check ok, then read
user, latencyMs, serverTime, or error from its result. ok means a 2xx
answer. userState says whether that answer named a user: identified, or
unavailable (for example an empty 204).
This health check does not confirm access to CLOCKIFY_WORKSPACE_ID. Make a
separate workspace-scoped request when you must verify the pinned workspace, as
shown in the compile-checked
first health-check example.
client.health() is a shortcut for the same check.
One sub-client per OpenAPI tag (33 modules). Two name shapes co-exist; the table summarises which is which.
| Cohort | Modules | Verbs |
|---|---|---|
| Pure CRUDL | tags, clients, projects, tasks, holidays, sharedReports, timeOffPolicies, userGroups, webhooks, expenses, expenseCategories |
list, create, get, update, delete (only the verbs the API supports) |
| CRUDL + action | expenseCategories.archive |
+ an action verb |
| Partial CRUDL | timeEntries, invoiceItems, invoicePayments, balanceAssignment (create / update / delete / get, no top-level list) |
Limited to what the API actually exposes (e.g. no top-level workspace LIST for timeEntries) |
| Workflow verbs | approvals (submit / resubmit / updateStatus), timeOff (submit / withdraw / changeTimeOffRequestStatus, the last operationId-derived), scheduling (publish / copy / recurring family) |
State-machine verbs that match upstream semantics |
| Mixed | invoices (CRUDL + filter / duplicate / export / updateStatus), reports (attendance / detailed / summary / weekly) |
CRUDL plus workflow actions; reports use family-name verbs |
| Scoped naming | customFields (listForWorkspace / listForProject / etc.) |
The module covers two surfaces; suffix disambiguates |
| OperationId-derived | files.uploadImage, expenseReport.generateDetailedReportV1, per-user workspaces.updateUser*, plus a handful of action verbs inside the stamped modules (timeEntries.deleteMany, scheduling.changeRecurringPeriod, webhooks.getWebhookEventStatusesWithLatestLog) |
Already verb-noun; rename buys nothing |
All 175 generated SDK operations are listed in
docs/resources/, one page per module.
Clockify list endpoints accept page (1-based, default 1) and
page-size (default 50, max 200). Responses are bare JSON
arrays. Most paginated endpoints emit a Last-Page header the wrapper
consumes as an authoritative end-of-pages signal.
iterAll — for "give me every record"A scoped Workspace exposes iterProjects / iterTags /
iterClients, which wrap iterAll with the workspaceId and the
fetcher wired for you — no .bind ritual:
import { createClockifyClient } from "@apet97/clockify115-sdk";
const ws = createClockifyClient().workspace("...");
for await (const project of ws.iterProjects({})) {
console.log(project.name);
}
iterAll(fetcher, baseRequest, options?) walks pages until the
server signals end-of-pages (via Last-Page: true if emitted,
else a non-full page). options: pageSize (default 50),
maxPages (default ∞), startPage (default 1, for resume flows).
For a resource without a scoped iterator (or to walk across
workspaces), call iterAll directly with a bound fetcher:
import { createClockifyClient, iterAll } from "@apet97/clockify115-sdk";
const client = createClockifyClient();
const listProjects = client.projects.list.bind(client.projects);
for await (const project of iterAll(listProjects, { workspaceId: "..." })) {
console.log(project.name);
}
.bind(client.projects)preserves the implicitthisand the method's full type signature. Bare references losethis; arrow wrappers lose type inference.
wrapResource — scope a resource module directlyA scoped Workspace builds ws.tags, ws.projects, and every other
sub-client with wrapResource internally: it injects workspaceId
into the first argument of each call. Call wrapResource yourself to
get that behavior on a bare resource client, or on any object that
takes the same single-request-object shape (e.g. a third-party client
with matching method signatures):
import { createClockifyClient, wrapResource } from "@apet97/clockify115-sdk";
const client = createClockifyClient();
const tags = wrapResource(client.tags, "...");
// workspaceId is injected automatically — no need to repeat it.
const list = await tags.list({});
Scoping supplies only workspaceId. A call such as ws.projects.create({ name })
still requires its project fields.
An explicit workspaceId passed in the request is still overridden by
the scoped value — the same rule Workspace uses.
Clockify's expense-list route ignores start and end. Use the exported
listExpensesFiltered helper instead of forwarding those inert query keys. It
walks the typed {expenses:{expenses:[...]}} envelope across bounded pages,
applies inclusive date-only or RFC3339 bounds (up to nine fractional digits) with an explicit Z/offset
client-side, and returns a warning plus lossless continuation metadata:
import { createClockifyClient, listExpensesFiltered } from "@apet97/clockify115-sdk";
const client = createClockifyClient();
const result = await listExpensesFiltered(
client.expenses.list.bind(client.expenses),
{ workspaceId: "..." },
{
start: "2026-06-01",
end: "2026-06-30T23:59:59Z",
limit: 100,
pageSize: 50,
maxPages: 20,
},
);
console.log(
result.items,
result.warnings,
result.meta.nextPage,
result.meta.nextOffset,
result.meta.nextMaxPages,
);
limit is the total returned-record cap; pageSize controls each wire
request. Last-Page is authoritative when present. Without it, the helper
uses page length plus the required bounded maxPages fallback. To resume,
pass meta.nextPage, meta.nextOffset, and meta.nextMaxPages; the offset
preserves records when the total limit stops inside a filtered page, while the
continuation-specific page bound stays runnable near the supported ceiling.
iterPages — for per-page envelopesimport { iterPages } from "@apet97/clockify115-sdk";
const listTags = client.tags.list.bind(client.tags);
for await (const { items, page, hasNextPage } of iterPages(
listTags,
{ workspaceId: "..." },
{ pageSize: 100 },
)) {
console.log(`page ${page}: ${items.length} tags (more: ${hasNextPage})`);
if (!hasNextPage) break;
}
paginatedList — a single passable handlepaginatedList(fetcher, baseRequest, options) wraps iterAll /
iterPages into one value you can return from a function or store in
state, then iterate, collect, or page through later:
import { createClockifyClient, paginatedList } from "@apet97/clockify115-sdk";
async function main(): Promise<void> {
const client = createClockifyClient();
const workspaceId = process.env.CLOCKIFY_WORKSPACE_ID!;
const allProjects = paginatedList(
client.projects.list.bind(client.projects),
{ workspaceId },
{ pageSize: 50 },
);
for await (const project of allProjects) {
console.log(project.name);
}
const first100 = await allProjects.toArray({ limit: 100 });
console.log(`first ${first100.length} projects`);
for await (const page of allProjects.pages()) {
console.log(`page ${page.page}: ${page.items.length} items (more: ${page.hasNextPage})`);
if (!page.hasNextPage) break;
}
}
This is purely additive to iterAll / iterPages above — use
whichever fits. iterAll is lighter weight when a bound method is
already at hand; paginatedList is preferable for a single value to
pass around (return from a function, store in state, call .toArray()
on later).
for (let page = 1; ; page++) {
const records = await client.users.list({
workspaceId: "...",
"include-roles": false,
page,
"page-size": 50,
});
if (records.length === 0) break;
for (const u of records) handle(u);
if (records.length < 50) break;
}
Every non-2xx throws a typed error:
| Class | Status | When |
|---|---|---|
ClockifyApiError |
(any) | Base. Carries statusCode, body, rawResponse, cause. |
BadRequestError |
400 | Malformed request body / query. |
UnauthorizedError |
401 | Missing or invalid X-Api-Key / X-Addon-Token. |
ForbiddenError |
403 | Authenticated but not permitted. |
NotFoundError |
404 | Resource doesn't exist or doesn't belong to this workspace. |
MethodNotAllowedError |
405 | Wrong verb (rare). |
ConflictError |
409 | Idempotency / uniqueness conflict (e.g. duplicate tag). |
RateLimitError |
429 | Rate limit exceeded. Carries retryAfterMs + rateLimitResetAt. |
InternalServerError |
500 | Upstream failure. |
ServiceUnavailableError |
503 | Backend overloaded or maintenance. |
ClockifyApiTimeoutError |
— | timeoutInSeconds elapsed before a response. |
AddonTokenRestrictionError |
401 | Add-on-token request hit an endpoint outside the add-on token's reach (body says "API is not accessible"), regardless of manifest scopes. Map a raw add-on-token 401 with mapAddonTokenRestriction; API-key 401s stay raw. |
code (from classifyClockifyError, see Error codes below)
and body (the raw server response) are the error contract: match on those
for retry logic, error routing, or user-facing messages. message is a
generic, generated string ("BadRequestError\nStatus code: 400") that does
not vary with the failure reason and is not documented per-code — it is a
debugging aid, not a machine-readable signal.
HTTP error classes and SDK timeouts share per-class Symbol.for markers
across compatible ESM and CommonJS builds in the same JavaScript agent.
An object with a matching status or name alone fails the HTTP error guards.
Code with access to the symbol registry can deliberately forge a marker.
If reading an HTTP error body fails, rawResponse retains the status and
headers (including Retry-After) and cause carries the read failure.
Caller cancellation and the request timeout still take precedence.
Use instanceof to handle a specific class:
import {
ClockifyApiError,
NotFoundError,
RateLimitError,
promoteApiError,
getRequestIdFromError,
} from "@apet97/clockify115-sdk";
try {
await client.tags.get({ workspaceId: "...", tagId: "deleted-tag-id" });
} catch (raw) {
// 429/409/500/503 are not in the OpenAPI spec per endpoint, so
// the generated client throws the base ClockifyApiError. `promoteApiError` swaps
// it for the matching subclass when one exists.
const err = promoteApiError(raw);
if (err instanceof NotFoundError) console.log("tag is gone");
else if (err instanceof RateLimitError) await sleep(err.retryAfterMs ?? 1000);
else if (err instanceof ClockifyApiError) {
console.error(
`request ${getRequestIdFromError(err)} failed with ${err.statusCode}:`,
err.body,
);
throw err;
}
}
getRequestIdFromError returns the request ID from the raw error response
when the server echoes X-Request-Id, or the server-side x-amz-cf-id
correlation ID when it does not. Clockify currently uses the latter response
header, so the helper gives logs a useful server correlation value without
pretending the request ID was echoed.
promoteApiError(err) is a no-op on values it doesn't recognise, so
it's safe to drop into any existing catch. Type-guard predicates
(isClockifyApiError, isRateLimitError, isConflictError,
isInternalServerError, isServiceUnavailableError) are exported
too if you prefer narrowing without re-allocating the error.
They classify by status, so they also match the base ClockifyApiError;
retryAfterMs / rateLimitResetAt exist only on a promoted RateLimitError,
and getRateLimitFromError(err) reads the same window off an unpromoted error.
try { await client.tags.list({ workspaceId }); }
catch (err) {
if (!isClockifyApiError(err)) throw err; // not from the SDK
if (isRateLimitError(err)) {
const resetAt = getRateLimitFromError(err)?.resetAt;
await sleep(resetAt != null ? Math.max(0, resetAt.getTime() - Date.now()) : 1000);
}
logger.error({ status: err.statusCode, requestId: getRequestIdFromError(err) });
}
getRateLimitFromError reads the window off a failed request. To read
it off a successful one — so you can back off before a 429 ever
happens — call getRateLimit on the headers withResponse exposes:
import { createClockifyClient, withResponse, getRateLimit } from "@apet97/clockify115-sdk";
const client = createClockifyClient();
const result = await withResponse(client.tags.list({ workspaceId: "..." }));
const rl = getRateLimit(result.headers);
if (rl.remaining !== undefined && rl.remaining < 5) {
console.warn(`${rl.remaining}/${rl.limit} requests remaining; resets at ${rl.resetAt}`);
}
Non-HTTP failures have three distinct paths:
| Value | Cause | Caller action |
|---|---|---|
ClockifyConnectionError after promoteApiError |
The underlying fetch failed before getting a response (DNS, TLS, ECONNRESET, TypeError: fetch failed). |
Retry with backoff; surface as an offline state. |
The exact AbortSignal.reason (AbortError for a default controller.abort()) |
The caller cancelled the operation. | Do not retry. |
ClockifyApiTimeoutError |
The request exceeded timeoutInSeconds. |
Retry with backoff when appropriate. |
import {
createClockifyClient,
isAbortError,
isConnectionError,
promoteApiError,
} from "@apet97/clockify115-sdk";
const client = createClockifyClient();
const controller = new AbortController();
try {
await client.tags.list({ workspaceId }, { abortSignal: controller.signal });
} catch (err) {
const e = promoteApiError(err);
if (isAbortError(e)) return; // default abort reason or promoted abort
if (isConnectionError(e)) {
// backoff and retry, or fail fast
}
throw e;
}
The generated request keeps signal.reason unchanged. isAbortError
recognizes the default AbortError shape and ClockifyAbortError.
If you call controller.abort(customReason), compare the caught value
with controller.signal.reason; an arbitrary custom value cannot be
identified as an abort without the signal that supplied it.
Use classifyClockifyError(err) when you want the same stable
recovery vocabulary used by the CLI and MCP surfaces:
import { classifyClockifyError } from "@apet97/clockify115-sdk";
try {
await client.tags.create({ workspaceId, name });
} catch (err) {
const classified = classifyClockifyError(err);
if (!classified) throw err;
if (classified.code === "rate_limited" && classified.retryable) {
// back off, then retry
return;
}
console.error(classified.code, classified.recovery);
throw err;
}
classifyClockifyError returns { code, recovery, retryable, statusCode?, serverCode?, message }. The stable code comes from
spec/surface/error-codes.json; serverCode preserves any Clockify
body-level code.
Use getStableErrorCode(err) when only the shared stable code is
needed. Use getErrorCode(err) when you specifically want the
server-side body code from Clockify:
import { getErrorCode, isClockifyApiError } from "@apet97/clockify115-sdk";
try {
await client.tags.create({ workspaceId, name });
} catch (err) {
// Clockify sends `code` as a JSON number; `getErrorCode` returns its
// string form. 501 is the catch-all validation code, which a duplicate
// name lands on — check the message to tell duplicates from other 501s.
if (isClockifyApiError(err) && getErrorCode(err) === "501") {
// graceful dedup
return;
}
throw err;
}
getErrorCode reads body.code first, then body.error.code;
returns undefined when neither is present.
By default the SDK retries 408 / 429 / 5xx up to 2 times with
exponential backoff (initial 1s, max 60s, ±20% jitter), honouring
Retry-After and X-RateLimit-Reset. Only read-only methods
(GET, HEAD, OPTIONS) retry by default. PUT, DELETE, POST,
and PATCH do not: a 5xx or transport failure on a write is
ambiguous — the server may have already applied it — so a blind
retry could double-apply a mutation.
Retrying PUT/DELETE is opt-in and available on every code path:
retryMutationMethods: true (client-level
createClockifyClient({ retryMutationMethods: true }) or
per-request client.tags.update(request, { retryMutationMethods: true })).composedFetch retry layer (only active when you
pass retryPolicy): add "PUT" / "DELETE" to
retryPolicy.retryableMethods.POST/PATCH are never auto-retried by either layer, regardless
of these options — they are not idempotent enough to retry blindly. Supplying
either method in retryPolicy.retryableMethods throws synchronously instead of
creating a policy that contradicts this guarantee.
When you pass retryPolicy, including false, the factory sets the generated
client's client-level maxRetries to 0. A policy object uses the
composedFetch retry layer, while false also disables that layer. A positive
per-request maxRetries overrides the client setting and can re-enable
generated retries, so do not combine it with retryPolicy. Omit retryPolicy
when you want the generated client's maxRetries option to apply.
const client = createClockifyClient({
retryPolicy: {
maxRetries: 5,
initialDelayMs: 500,
maxDelayMs: 30_000,
jitter: 0.3,
retryableStatusCodes: [500, 502, 503, 504],
retryableMethods: ["GET", "HEAD", "OPTIONS"],
},
});
// Typed methods: opt in per client or per request.
const client = createClockifyClient({ retryMutationMethods: true });
await client.tags.update(request, { retryMutationMethods: true });
// composedFetch's own retry layer (only relevant if you also pass retryPolicy):
const withCustomPolicy = createClockifyClient({
retryPolicy: { retryableMethods: ["GET", "HEAD", "OPTIONS", "PUT", "DELETE"] },
});
const client = createClockifyClient({ retryPolicy: false });
const client = createClockifyClient({
retryPolicy: {
computeDelay: (attempt, response) => {
// Replaces the built-in delay, Retry-After handling included:
// the header is either whole seconds or a date.
const header = response?.headers.get("Retry-After")?.trim();
if (header) {
const wait = /^\d+$/.test(header) ? Number(header) * 1000 : Date.parse(header) - Date.now();
if (wait >= 0) return Math.min(wait, 60_000);
}
return Math.min(1000 * 2 ** attempt, 30_000);
},
},
});
await client.tags.list({ workspaceId: "..." }, { maxRetries: 0 });
classifyWriteOutcome(err) turns the ambiguity above into an explicit
value instead of leaving every catch site to re-derive it: a timeout, a
connection failure/abort (no HTTP response at all), or a 5xx is
"possibly-committed" — the write may already be applied server-side; a
4xx is "definitely-failed" — the server rejected it before applying
anything. Anything else (a non-SDK error, or a status this SDK does not
classify) is "unknown". Classification only — it does not retry or
change the defaults above. If you opted writes into retries
(retryMutationMethods, or PUT/DELETE in retryPolicy.retryableMethods) and an
earlier attempt had an ambiguous outcome, the final 4xx (e.g. DELETE: 502 then
404) is still "possibly-committed": the earlier attempt may have applied.
import { classifyWriteOutcome, createClockifyClient } from "@apet97/clockify115-sdk";
const client = createClockifyClient();
try {
await client.timeEntries.create({ workspaceId, body });
} catch (err) {
switch (classifyWriteOutcome(err)) {
case "possibly-committed":
// check whether the entry actually landed before retrying
break;
case "definitely-failed":
throw err; // fix the request and retry freely
case "unknown":
throw err;
}
}
const client = createClockifyClient({ timeoutInSeconds: 10 });
const ctrl = new AbortController();
setTimeout(() => ctrl.abort(), 5000);
await client.projects.list(
{ workspaceId: "..." },
{ timeoutInSeconds: 3, abortSignal: ctrl.signal },
);
Timeouts throw ClockifyApiTimeoutError. Caller aborts reject with the
effective signal's exact reason (including custom Error or primitive
reasons), so cancellation remains distinguishable from SDK timeouts.
timeoutMs shorthandThe axioms doc and most of the JS ecosystem use milliseconds
(setTimeout(ms), AbortSignal.timeout(ms)). The generated per-call
option is timeoutInSeconds. The conversion is straightforward:
import { createClockifyClient } from "@apet97/clockify115-sdk";
const client = createClockifyClient();
// 5-second timeout, expressed two equivalent ways:
await client.tags.list({ workspaceId }, { timeoutInSeconds: 5 });
await client.tags.list({ workspaceId }, { timeoutInSeconds: 5_000 / 1_000 });
// Or define a one-line helper at your call site if you prefer ms:
const ms = (n: number) => ({ timeoutInSeconds: n / 1_000 });
await client.tags.list({ workspaceId }, ms(5_000));
We don't ship a timeoutMs field on RequestOptions because
adding a generated-client-overlapping field would create two ways to spell the
same thing — small ergonomic gain, real risk of "set both,
which one wins?" footguns. The conversion is a single division
when you want it.
The generated client already takes per-call options as its last argument
(maxRetries, timeoutInSeconds, abortSignal, queryParams, headers).
The request-options subpath gives them a stable public type and small
builders so you never reach into generated internals:
import {
createClockifyClient,
requestOptions,
withHeaders,
withRequestTimeout,
} from "@apet97/clockify115-sdk";
const client = createClockifyClient();
await client.tags.list(
{ workspaceId },
requestOptions({
...withRequestTimeout(10),
...withHeaders({ "X-Request-Id": "tags-page-1" }),
}),
);
ClockifyRequestOptions omits addonToken — auth belongs on the client, not
on individual calls. Header values are stringified; withRequestTimeout
rejects non-positive timeouts and withIdempotencyKey rejects empty keys
(see Idempotency keys).
toOperationReceipt() wraps a generated call in the same receipt vocabulary
the CLI and MCP surfaces emit — status, headers, requestId, rateLimit,
changed, warnings, next — without swallowing errors:
import { createClockifyClient, toOperationReceipt } from "@apet97/clockify115-sdk";
const client = createClockifyClient();
const receipt = await toOperationReceipt(client.tags.list({ workspaceId }), {
action: "tags.list",
changed: false,
next: ["Use iterAll for a full paginated walk."],
});
console.log(receipt.status, receipt.requestId, receipt.data);
Errors still throw. Catch them and call toOperationErrorReceipt() for the
matching error receipt with a stable code, retryable flag, and recovery
hints. For a write, pass { write: true } and decide on replaySafe.
retryable describes the error alone: it stays true for a lost response
whose write may already have applied.
import { toOperationErrorReceipt } from "@apet97/clockify115-sdk";
try {
await toOperationReceipt(client.tags.list({ workspaceId }), { action: "tags.list" });
} catch (error) {
const receipt = toOperationErrorReceipt("tags.list", error);
console.error(receipt.code, receipt.recovery);
}
try {
await toOperationReceipt(client.tags.create({ workspaceId, name }), { action: "tags.create" });
} catch (error) {
const receipt = toOperationErrorReceipt("tags.create", error, [], { write: true });
if (receipt.replaySafe) {
console.error("Clockify refused the write:", receipt.code, receipt.recovery);
} else {
console.error("The write may have applied:", receipt.recovery); // read back first
}
}
Most Clockify updates replace the whole record: a field you leave out is reset.
@apet97/clockify115-sdk/updates reads the current record, merges your change and
sends the complete body. It sends nothing when every field you give already has
that value; a reordered list counts as a change, and so does a policy's
hasExpiration, which no read returns. It throws UnsafeUpdateError
when the record cannot be written back, for example because it lacks a field that
the update would reset, and TypeError for a field it does not know or a value of
the wrong type.
import { clientUpdate } from "@apet97/clockify115-sdk/updates";
const { entity, changed } = await clientUpdate.apply(
client,
{ workspaceId, clientId },
{ note: "Invoices go to accounting." }, // the CC list, address and e-mail are kept
);
console.log(changed); // ["note"]
There is one for each entity: clientUpdate, customFieldUpdate,
expenseCategoryUpdate, holidayUpdate, invoiceUpdate, projectUpdate,
tagUpdate, taskUpdate, timeEntryUpdate, timeOffPolicyUpdate and
webhookUpdate. Use update.changed(record, patch) and
update.body(record, patch) to preview a change or to send it yourself.
A list in the patch replaces the list. An object is merged: the parts of a
policy's approve, automaticAccrual, automaticTimeEntryCreation and
negativeBalance and of a holiday's datePeriod that you leave out stay as they
are. timeOffPolicyUpdate needs hasExpiration in every patch, because Clockify
never returns it. It never returns the color of a holiday either, so pass color
to holidayUpdate if it has one.
invoiceUpdate adds TAX to visibleZeroFields when the invoice has a tax, and
refuses an invoice with an item that would lose or gain a tax, unless the patch
sets taxPercent: the update would make every item apply only the first tax.
Another write between the read and the update is overwritten: Clockify has no conditional writes. An invoice is read back after its update. If only that fails, the error says that the invoice was updated.
Some records have no route of their own. @apet97/clockify115-sdk/lookup finds
them in their list: findCustomField, findExpenseCategory, findHoliday,
findTimeOffRequest and findUserGroup. undefined means that every page was
read. listGroupMembers reads every member of a user group.
@apet97/clockify115-sdk/timer finds and stops the running timer of one user. The
documented routes for a group's members and for stopping a timer do not work, so
the client has no method for them.
import { stopRunningEntry } from "@apet97/clockify115-sdk/timer";
const stopped = await stopRunningEntry(client, { workspaceId, userId });
console.log(stopped.running ? `stopped ${stopped.entry.id}` : "no timer was running");
@apet97/clockify115-sdk/operations describes every operation of the API as data:
method, path, host, effect, JSON schema of the input, and the MCP tool and CLI
command that cover it. Use it to find an operation, check input before sending
it, and call an operation chosen at run time. Importing /operations is the
only way to load the catalog; nothing else in the SDK pulls it in.
import { callOperation, findOperation, operationInputProblems, searchOperations } from "@apet97/clockify115-sdk/operations";
const [operation] = searchOperations("archive a client");
if (operation) {
console.log(operation.name, operation.effect, operation.replacedBy); // clients.update business_write clientUpdate
operationInputProblems(operation, { workspaceId, path: { clientId } }); // ['body.name is missing']
}
const tags = await callOperation(client, "tags.list", { workspaceId, query: { archived: false } });
findOperation accepts the SDK name (tags.list), the operationId or the exact
MCP name. callOperation is typed by the name, goes through the same client as
a generated method, and throws OperationInputError before any request when the
input does not match the schema. effect is read, business_write,
external_side_effect, privileged or destructive. replacedBy names the
merge-safe function on /updates for an operation that replaces the record.
Feed a structured logger from hooks:
const client = createClockifyClient({
hooks: {
afterResponse: ({ method, response, durationMs, requestId }) =>
console.info("clockify.response", { method, status: response.status, durationMs, requestId }),
onRetry: ({ method, nextAttempt, delayMs, requestId }) =>
console.warn("clockify.retry", { method, nextAttempt, delayMs, requestId }),
onError: ({ method, error, durationMs, requestId }) =>
console.error("clockify.error", { method, error: String(error), durationMs, requestId }),
},
});
Every HTTP status reaches afterResponse, 4xx and 5xx included. onError
reports an attempt that got no usable response: a transport failure, an abort or
a blocked redirect. Hooks receive the live ctx.headers, which carry X-Api-Key
or X-Addon-Token, and the unredacted ctx.url. Redact both if you log them.
For a wired Pino-shaped logger see
examples/structured-logging.ts.
During development, debug prints one console.debug line per request,
response, error and retry. It logs no headers and redacts credential-shaped
query values:
const client = createClockifyClient({ debug: true });
A retry event needs a retryPolicy. Without one the generated client retries on
its own, and each retry reads as one more request and response.
The client also accepts a logging option. The SDK sends it no request events,
so a logger passed there stays silent.
This Node.js example uses the optional undici package for its proxy dispatcher.
import { ProxyAgent } from "undici";
const dispatcher = new ProxyAgent("http://proxy.local:8080");
const client = createClockifyClient({
fetch: (input, init) => {
const options = { ...init, dispatcher };
return fetch(input, options);
},
});
createClockifyClient still wraps your fetch with
composedFetch for User-Agent + X-Request-Id injection. Pass
userAgent: false or requestId: false to opt out if your proxy
already does that.
Clockify sends a webhook's 32-character signing secret in the
Clockify-Signature header and the event name in
Clockify-Webhook-Event-Type. The body is the entity itself, without an
envelope. createWebhookReceiver checks the secret before it reads the body,
limits the body size and calls one typed handler per event:
import { createTestDelivery, createWebhookReceiver } from "@apet97/clockify115-sdk/webhooks";
const token = process.env.CLOCKIFY_WEBHOOK_TOKEN ?? "demo-token-32-chars-aaaaaaaaaaaa";
export const receiver = createWebhookReceiver({
expectedToken: token,
handlers: {
NEW_TIME_ENTRY: (entry) => console.log("new entry:", entry.id, entry.timeInterval.start),
TIMER_STOPPED: (entry) => console.log("timer stopped:", entry.id),
},
onUnhandled: ({ event }) => console.log("no handler for", event),
onError: (error) => console.error("delivery failed:", error),
});
const { headers, body } = createTestDelivery({
event: "NEW_TIME_ENTRY",
payload: {
id: "65f7c3a4b8e8a31234567891",
description: "Support",
tagIds: [],
userId: "65a3a1c8e8a31234567890ab",
billable: true,
taskId: null,
projectId: null,
timeInterval: {
start: "2026-05-24T10:00:00Z",
end: "2026-05-24T11:00:00Z",
duration: "PT1H",
},
workspaceId: "0123456789abcdef01234567",
isLocked: false,
hourlyRate: null,
costRate: null,
customFieldValues: [],
},
token,
});
const post = (init: RequestInit) =>
receiver.fetch(new Request("http://localhost/clockify", { method: "POST", ...init }));
console.log("signed:", (await post({ headers, body })).status);
console.log("unsigned:", (await post({ body })).status);
receiver.fetch takes a web Request and returns a Response.
receiver.node is a Node request listener:
import { createServer } from "node:http";
createServer(receiver.node).listen(8080);
| Status | Meaning |
|---|---|
200 |
Accepted. Without a handler or an event header it goes to onUnhandled |
400 |
The body is not JSON or could not be read |
401 |
The secret is missing or wrong |
405 |
The method is not POST |
413 |
The body is larger than maxBodyBytes (1 MiB by default) |
500 |
A handler failed; Clockify delivers the event again |
To verify a delivery yourself, use verifyClockifyWebhook (boolean) or
constructEvent (throws, returns the typed payload):
import { verifyClockifyWebhook } from "@apet97/clockify115-sdk";
if (!verifyClockifyWebhook({ headers: req.headers, expectedToken: secret })) {
return res.status(401).send("invalid");
}
Both accept headers as Headers, Map<string,string>,
Record<string, string|string[]>, or Array<[name, value]>, and accept several
secrets so a secret can be rotated without rejecting deliveries. They also accept
the older header name Clockify-Signature-Token. The scheme is a shared
secret, not an HMAC over the body: treat it as a credential, and use HTTPS.
Deliveries are at least once and can repeat: a retry carries the same body and a
different Idempotency-Key, so deduplicate by the entity in the body, not by
that header. Find the deliveries your endpoint missed in the last seven days with
undeliveredWebhookEvents. It reads every page, and throws when maxPages stops
it before the end:
import { undeliveredWebhookEvents } from "@apet97/clockify115-sdk/webhooks";
for await (const missed of undeliveredWebhookEvents(client, { workspaceId, webhookId })) {
console.log(missed);
}
The payload types describe what Clockify documents and what was recorded from
live deliveries. constructEvent does not validate the payload at runtime.
createClockifyClient accepts lifecycle hooks for observability
piping (Datadog, Honeycomb, structured logs, retry telemetry):
const client = createClockifyClient({
hooks: {
beforeRequest: ({ method, url, requestId }) =>
logger.info({ method, url, requestId }, "→ request"),
afterResponse: ({ response, durationMs, requestId }) =>
metrics.histogram("clockify.duration", durationMs, {
status: response.status,
requestId,
}),
onError: ({ error, durationMs, requestId }) =>
logger.error({ error, durationMs, requestId }, "× request failed"),
onRetry: ({ nextAttempt, delayMs, requestId }) =>
logger.warn({ nextAttempt, delayMs, requestId }, "↻ retrying"),
},
});
Hooks are best-effort: a hook that throws is logged via
console.warn but never blocks the request. Hooks may be sync or
return a Promise.
A response body can be read once. A hook that needs it must read a clone, so the caller can still read the original:
const client = createClockifyClient({
hooks: {
afterResponse: async ({ response }) => {
console.log(await response.clone().json());
},
},
});
To reuse the composed fetch outside the SDK (e.g. wrap another SDK with the same observability layer):
import { composedFetch } from "@apet97/clockify115-sdk/composed-fetch";
const myFetch = composedFetch({
hooks: { beforeRequest: ({ method }) => console.debug(method) },
retryPolicy: { maxRetries: 5 },
});
@apet97/clockify115-sdk/otel-hooks turns the same lifecycle hooks into
OpenTelemetry HTTP semantic-convention (v1.27, stable) span
attributes. Bring your own tracer — the SDK does not depend on
@opentelemetry/api at runtime, only on the convention strings:
import { createClockifyClient } from "@apet97/clockify115-sdk";
import { otelHooks, type OtelLikeSpan } from "@apet97/clockify115-sdk/otel-hooks";
import { trace } from "@opentelemetry/api";
const tracer = trace.getTracer("my-app");
const client = createClockifyClient({
hooks: otelHooks({
startSpan: (name, attrs) => {
const span = tracer.startSpan(name);
if (attrs) for (const [k, v] of Object.entries(attrs)) span.setAttribute(k, v);
return span as unknown as OtelLikeSpan;
},
}),
});
otelHooks(...) returns a plain hooks object, so it composes with any
other hook set from the section above.
Clockify's server does not currently honor Idempotency-Key
headers. The SDK still lets you set the
header on any write — the value passes through unchanged so that:
import { createClockifyClient } from "@apet97/clockify115-sdk";
import { randomUUID } from "node:crypto";
const client = createClockifyClient();
const tag = await client.tags.create(
{ workspaceId, name: "weekly-review" },
{ headers: { "Idempotency-Key": randomUUID() } },
);
The header threads through the generated client's RequestOptions.headers and is
sent on the wire as Idempotency-Key: <uuid>. See
examples/pass-idempotency-key.ts for a runnable script.
// ESM
import { createClockifyClient } from "@apet97/clockify115-sdk";
// CommonJS
const { createClockifyClient } = require("@apet97/clockify115-sdk");
Both module systems resolve via the modern dual-tier exports
map (import/require, each { types, default }). TypeScript picks the correct .d.ts per consumer's
moduleResolution. Subpaths (@apet97/clockify115-sdk/iter,
/webhooks, /composed-fetch, /create-client, /diagnostics,
/with-response) work in both. The
/with-response subpath ships the withResponse(...) helper for
lifting HttpResponsePromise into a flat { data, response, headers, requestId, status } shape:
import { createClockifyClient, withResponse } from "@apet97/clockify115-sdk";
const client = createClockifyClient();
const { data: tags, requestId, status, headers } = await withResponse(
client.tags.list({ workspaceId: "..." }),
);
console.log(`request ${requestId} returned ${status} with ${tags.length} tags`);
console.log(`server rate-limit: ${headers.get("X-RateLimit-Remaining")}`);
Use withResponse when the parsed body alone is not enough — status,
headers, or a correlation ID for logs. Plain await client.tags.list(...)
stays the right shape for the common case (body only). Errors thrown
by the wrapped method propagate unchanged; withResponse only
restructures the success path.
| You want to… | Use | Subpath |
|---|---|---|
| Turn a name/"me" into a real id (or a grounded "did you mean?") | resolveEntityRef, resolveUserRef, matchByName |
@apet97/clockify115-sdk/resolve |
| Resolve a list of user/group/tag names (or a single user filter) to ids in one call | resolveUserRefs, resolveGroupRefs, resolveTagRefs, resolveUserFilter |
@apet97/clockify115-sdk/resolve |
| Create a tag/project/client only if it does not already exist | ensureTag, ensureProject, ensureClient (or ws.ensureTag/ensureProject/ensureClient on a scoped client) |
@apet97/clockify115-sdk/ensure |
| Delete a project/client the way the live API allows (GET name → archive → delete; clients use the body-envelope archive quirk) | archiveThenDeleteProject, archiveThenDeleteClient |
@apet97/clockify115-sdk/ensure |
| Encode Clockify's non-uniform money units | toMinor, toMajor, expenseAmountToWire, invoiceItemUnitPrice* |
@apet97/clockify115-sdk/money |
| Change an invoice and keep the rest of it, its taxes included | invoiceUpdate |
@apet97/clockify115-sdk/updates |
| Resolve relative dates server-side ("yesterday", periods) and validate weekly windows | resolveRelativeDay, resolvePeriod, parseWeeklyDateTime, isExactWeeklyRange |
@apet97/clockify115-sdk (or @apet97/clockify115-sdk/dates) |
| Build typed report filters + narrow report responses | summaryFilter, detailedFilter, detailedEntries |
@apet97/clockify115-sdk/reports |
| Run a bounded-parallel bulk operation with collected failures | mapBounded |
@apet97/clockify115-sdk/bulk |
Archive/delete helpers take an ArchiveThenDeleteAdapter<TCurrent> with typed
getCurrent, archive, and delete callbacks; see the compile-checked
SDK Helper Cookbook. Clients must preserve editable
state in the replacement-body archive request; see the compile-checked
client adapter example.
The ensure helpers are pure (you inject list/create/archive/delete),
so they reuse instead of duplicating on a re-run — Clockify does not enforce
name uniqueness, so a naive create silently makes a second "Acme".
The SDK requires Node 22.13 or newer and is tested on Node 22.13, 24, and 26.
| Runtime | Minimum | Tested |
|---|---|---|
| Node.js | 22.13.0 (global fetch, AbortSignal.timeout, randomUUID) |
22.13, 24, 26 (CI) |
| TypeScript | 5.0 (published types are verified under moduleResolution: "Bundler", a TypeScript 5.0 mode) |
7.x (workspace dev dependency), 5.x consumer contract |
| Bun | expected to work; not exercised in CI | not in CI |
| Deno | expected to work via npm: specifier; not exercised in CI |
not in CI |
| Browsers | read-only flows work; do NOT ship apiKey to a browser |
not in CI |
CHANGELOG.md.MIT — see LICENSE.