Skip to main content

TypeScript / JavaScript SDK

@k9o/core is the canonical reference SDK for the Kilimanjaro platform. It covers the full API surface — data (collections, query builder, storage), auth (Gate), realtime subscriptions, functions, policies, audit log, and org management. Chapter 13 of the platform specification is TypeScript-first; every other language SDK mirrors this surface with per-language casing applied.

Runtime support: Node 20+, Bun 1.1+, browsers (es2022 target). Ships as ESM and CJS; exports are tree-shakeable per pillar. A mobile shim (@k9o/gate-react-native) wraps this package for React Native auth use cases.


Installation​

npm install @k9o/core

Package coordinate: @k9o/core on npm.


Setup​

Construct a client with your org slug, project slug, and API key. baseUrl is optional — the default is https://api.k9o.io; when you pass the bare apex together with orgSlug, the SDK derives the canonical https://<orgSlug>.api.k9o.io for you. The snippet below shows the explicit subdomain form for clarity, but it is omittable. Self-hosted and Sovereign deployments pass their own host. A path-bearing URL throws K9O_INVALID_BASE_URL at construction time, before any network request is made.

TypeScript
import { createClient, KError } from "@k9o/core";

const k9o = createClient({
baseUrl: "https://acme.api.k9o.io", // optional; omit to default to https://api.k9o.io
apiKey: process.env.K9O_API_KEY,
orgSlug: "acme",
projectSlug: "member-portal",
});

Showing example in TypeScript

API key discipline. Source your key from an environment variable (K9O_API_KEY is the conventional name). The SDK does not infer the org from the key — orgSlug is always required. Keys are minted per project in the Console.

Self-hosted and Sovereign deployments​

For self-hosted and Sovereign Control deployments, override baseUrl with your own host. The value must be a scheme + host only — no path segment. Passing a path-bearing URL (for example https://api.k9o.io/v2) throws K9O_INVALID_BASE_URL at construction time, before any network request is made.

TypeScript
import { createClient } from "@k9o/core";

const k9o = createClient({
baseUrl: "https://platform.acme.internal", // scheme + host only
apiKey: process.env.K9O_API_KEY,
orgSlug: "acme",
projectSlug: "member-portal",
});

// Local development
const dev = createClient({
baseUrl: "http://localhost:8080",
apiKey: process.env.K9O_API_KEY,
orgSlug: "acme",
projectSlug: "member-portal",
});

Showing example in TypeScript


Getting started​

The first operation most applications make is querying a data collection — build a query, await it, and handle KError. Signing users in has its own section below.

TypeScript
import { createClient, KError } from "@k9o/core";

const k9o = createClient({
baseUrl: "https://acme.api.k9o.io", // optional; omit to default to https://api.k9o.io
apiKey: process.env.K9O_API_KEY,
orgSlug: "acme",
projectSlug: "member-portal",
});

try {
const { data, meta } = await k9o.from("posts").select().eq("status", "published").limit(10);
console.log(data, meta.cursor);
} catch (e) {
if (e instanceof KError) console.error(e.code, e.message, e.recommendation);
}
Output · bash
[ { id: 'post_1', title: 'Hello', status: 'published' } ] { next: null }

Showing example in TypeScript

k9o.from(collection).select() returns { data, meta } on success or throws KError on failure. Chaining .eq(), .limit(), and similar builder methods narrows the result set before execution. The example above demonstrates the pattern: build a query, destructure the response, and handle KError in the catch block.

k9o.from(collection) targets a collection (Postgres table) in your project's user-data schema. select() takes no arguments; narrow the result with filters (eq, neq, gt, gte, lt, lte, in, like, ilike, is), limit, cursor, and count. insert, update, and delete write rows; update and delete target a row with .eq("id", ...). Queries respect tenant scoping and compose with the policy-layer row-level security. For the full query surface see the Data API reference.


Authenticating your End-Users​

Gate signs in your project's end users — distinct from the operator credentials you use for the Console. Password is the simplest path; for the social and passwordless flows that increasingly replace it, Gate exposes one method per flow. A password sign-in returns the session synchronously; the identity-provider redirect flow hands control to the provider and returns through your callback page.

Password
const { data } = await k9o.gate.signIn({ email: "[email protected]", password: "…" });
console.log("signed in:", data.user.id); // the eu_<base62> end-user id
const accessToken = data.session.accessToken;
Output · bash
signed in: eu_8f3kQ2mZ

Showing example in Password

gate.revokeAllSessions ends every session of the signed-in user, this device included; access tokens already issued live until they expire. See Session lifetime and sign-out.

signInWithProvider runs in a browser and accepts google, github, microsoft, oidc and saml — saml federates into your customers' enterprise IdPs. Each provider is configured once for the project. A magic-link redirectUrl must be registered in your project's redirect allowlist; a non-allowlisted value is rejected with K9O_GATE_REDIRECT_NOT_ALLOWED. See the Auth API reference for provider setup and the full Gate method surface (signUp, signOut, refresh, whoami, MFA, and the session shape).


Handling errors​

The TypeScript SDK uses throw-on-error delivery. Every method returns Response<T> on success or throws KError on failure. There is no .orThrow() companion, no dual safe() variant, and no chainable Result hybrid — the mode is single.

TypeScript
import { createClient, KError } from "@k9o/core";

const k9o = createClient({
baseUrl: "https://acme.api.k9o.io", // optional; omit to default to https://api.k9o.io
apiKey: process.env.K9O_API_KEY,
orgSlug: "acme",
projectSlug: "member-portal",
});

try {
const { data, meta } = await k9o.from("posts").select();
console.log(data, meta.cursor)
} catch (e) {
if (e instanceof KError) {
  switch (e.code) {
    case 'K9O_TIER_CAP_HIT':
      // e.recommendation is text when present, otherwise null
      console.error('Tier cap reached:', e.message, e.recommendation)
      break
    case 'K9O_COLLECTION_NOT_FOUND':
      // e.context names the collection the caller supplied
      console.error('Collection not found:', e.context)
      break
    case 'K9O_ACCESS_DENIED':
      console.error('Access denied:', e.context)
      break
    default:
      console.error(`[${e.code}] ${e.message}`)
  }
} else {
  throw e
}
}
// Output (illustrative; on failure, one line prints depending on the error code):
// Tier cap reached: <message> <recommendation>
// Collection not found: <context>
// Access denied: <context>
// [<code>] <message>
Output · bash
[ { id: 'post_1', title: 'Hello' } ] { next: null }

Showing example in TypeScript

KError shape​

Every platform error — at the SDK surface, on the wire, and in CLI structured output — is a KError:

class KError extends Error {
code: string // SCREAMING_SNAKE_CASE; closed taxonomy
message: string // human-readable; safe to log and surface
context: object // family-specific structured fields per code (read-only)
recommendation: string | null // optional remediation hint
status: number | null // HTTP status, when the error came from the wire
requestId: string | null // correlation ID of the failed request
}

code is drawn from a closed taxonomy. A selection of codes you are likely to handle:

CodeFamilyWhen it fires
K9O_UNAUTHENTICATEDAuthCredentials missing or invalid
K9O_INVALID_CREDENTIALSAuthEmail / password mismatch on gate.signIn
K9O_ACCESS_DENIEDAuthorityCaller authenticated but lacks the required role
K9O_COLLECTION_NOT_FOUNDResourceThe named collection does not exist in the project
K9O_END_USER_NOT_FOUNDResourceGate end-user lookup returned no record
K9O_TIER_CAP_HITCapacityA tier-bound cap (MAU, storage, etc.) was reached
K9O_TIER_RATE_LIMIT_EXCEEDEDCapacityPer-period rate limit exceeded
K9O_INJECTION_DETECTEDValidationThe four-layer anti-injection posture rejected the request
K9O_INVALID_BASE_URLValidationcreateClient received a path-bearing or scheme-less baseUrl

The recommendation field is text when present and null otherwise; do not assume it is present. K9O_INJECTION_DETECTED is the wire code the gateway returns; the SDK-local K9O_INVALID_BASE_URL is raised by createClient before any request is made. See the error catalogue for the full taxonomy.


Response envelope and meta​

Every successful call returns { data, meta }. meta is always present and structured as namespaces — not flat fields:

TypeScript
import type { MetaCursor, MetaTiming, MetaContext } from '@k9o/core'

const response = await k9o.from('posts').select()

// meta is typed as Record<string, unknown>; narrow it before reading.

// Pagination (present on list responses)
const cursor = response.meta.cursor as MetaCursor
cursor.next          // opaque base64 cursor; null on the final page
cursor.totalCount    // integer total when count mode is not 'none'

// Request context (always present)
const context = response.meta.context as MetaContext
context.requestId    // trace / correlation ID for this call

// Cost attribution (present when dimensions were touched)
const cost = response.meta.cost as Record<string, number>
cost.apiCalls        // API calls billed for this request

// Timing (always present)
const timing = response.meta.timing as MetaTiming
timing.totalMs       // total gateway latency for this call

// Non-fatal warnings on a successful call (absent when empty)
// Each entry: { code: string, message: string }
response.meta.warnings

Showing example in TypeScript

All field names on meta are camelCase in TypeScript per the ch13 casing rule. The wire format is always camelCase JSON regardless of which language SDK you use.


Async / realtime subscriptions​

The TypeScript SDK delivers realtime events as an async iterator — for await...of. The wire transport is Server-Sent Events (SSE); a stream lasts up to 300 seconds; to continue after it ends, reconnect with the last event id as Last-Event-ID and drop duplicates by eventId (the client contract, see the Realtime API reference). A resync frame means re-read the data. There is no initial-state replay: read the current rows with select(), then subscribe for changes. Each event is { topic, eventType, payload, occurredAt, eventId }.

TypeScript
import { createClient, realtimeTopic } from "@k9o/core";

const k9o = createClient({
baseUrl: "https://acme.api.k9o.io", // optional; omit to default to https://api.k9o.io
apiKey: process.env.K9O_API_KEY,
orgSlug: "acme",
projectSlug: "member-portal",
});

for await (const event of k9o.realtime.subscribe(realtimeTopic.collection("posts"))) {
console.log(event.eventType, event.payload);
}
Output · bash
row_inserted { id: 'order-124', total: 42 }
row_updated { id: 'order-124', total: 45 }
row_deleted { id: 'order-124' }

Showing example in TypeScript

For topics and the frame format, see the realtime reference.

Streams​

Streams are ordered and replayable. maxBytes is at least 10485760 (10 MiB), and the stream's slug (derived from the display name) is what the other calls take. event.sequence is a string.

TypeScript
await k9o.streams.create({ displayName: "orders", maxBytes: 10_485_760 });
await k9o.streams.publish("orders", { id: 1, total: 42 }, { subject: "eu.new" });
await k9o.streams.publish("orders", { id: 2, total: 17 });

const controller = new AbortController();
for await (const event of k9o.streams.subscribe("orders", { fromSequence: 0, signal: controller.signal })) {
console.log(event.sequence, JSON.stringify(event.data)); // 1 {"id":1,"total":42}
if (event.sequence === "2") controller.abort();
}

const { data: page } = await k9o.streams.replay("orders", { fromSequence: 0, limit: 10 });
console.log(page.events.length, page.hasMore);
Output · bash
1 {"id":1,"total":42}
2 {"id":2,"total":17}
2 false

Showing example in TypeScript


See also​

  • API conventions — response envelope, KError shape, naming, pagination, versioning
  • Auth API reference — Gate IAK sign-in methods, MFA, session lifecycle, token shapes
  • Data API reference — collections, query modes, migrations, storage, realtime
  • CLI reference — the k9o CLI uses the same wire shape in structured-output mode
  • Other SDKs — Python, Go, Rust, Java, .NET, Ruby, PHP, Kotlin, Swift, Dart, React Native