JavaScript / TypeScript SDK
The official JavaScript and TypeScript libraries for the OctaSpace API.
Package | Use it for |
|---|---|
The API client: Node.js 22+, browsers, Deno and Bun; no dependencies | |
Query options and keys for TanStack Query v5, with any adapter (React, Vue, Solid...) | |
React context and hooks, for apps without TanStack Query |
Source and changelogs: GitHub. Every type and method has TSDoc comments, which your editor shows as you type.
Installation
npm install @octaspace/sdkThe package ships ESM and CommonJS builds with type definitions and uses the built-in fetch.
Create a client
import { OctaClient } from '@octaspace/sdk'
const client = new OctaClient({ apiKey: process.env.OCTA_API_KEY })Create one client and reuse it. Without apiKey only the public endpoints work.
Options
Option | Default | Effect |
|---|---|---|
apiKey | none | Your API key |
timeoutMs | 30000 | Time limit of one HTTP request; each retry gets its own |
retries | 2 | Retries of failed GET requests; 0 turns them off |
userAgent | @octaspace/sdk/<version> (js) | User-Agent header |
onRequest, onResponse | none | Hooks for logging and metrics. request.headers contains your key: do not log them as a whole |
fetch | globalThis.fetch | Your own fetch, for a proxy or tests |
baseUrl | https://api.octa.space | Another API host |
baseUrls | none | Ordered list of hosts; a GET moves to the next one only when the current one cannot be reached |
Every read method takes an optional last argument { signal, retries } for that call only:
const controller = new AbortController()
setTimeout(() => controller.abort(), 5_000)
const info = await client.network.info({ signal: controller.signal })Resources
Resource | Methods |
|---|---|
client.accounts | balance |
client.compute | list, apps, start, startBatch, restart |
client.render | list, start, startBatch |
client.vpn | list, start |
client.sessions | list, get, logs, stop, waitReady, waitStopped |
client.hosting | nodes, get, setPrices |
client.network | info, history |
client.stats | gpuCurrent, gpuHistory, gpuLocations, mining |
Node maintenance is not in the JavaScript SDK yet; use PUT / DELETE /hosting/nodes/{number}/maintenance or the CLI.
Methods return the API's JSON as plain objects; fields the types do not list yet are kept.
Examples
Start a session and wait for it
import { OctaSessionStoppedError } from '@octaspace/sdk'
const { uuid } = await client.compute.start({
node_number: '7KQ4-M2XD-4',
image: 'ubuntu:24.04',
disk_size: 20,
ssh: true,
})
try {
const session = await client.sessions.waitReady(uuid, {
timeoutMs: 10 * 60_000,
onProgress: (s) => console.log(s.status, s.progress, s.pull_percent),
})
console.log(session.ssh?.proxy)
} catch (err) {
if (err instanceof OctaSessionStoppedError) {
// the session stopped while starting
} else {
throw err
}
}Money
import { formatUsd, usdToMicroUsd } from '@octaspace/sdk'
const { balance } = await client.accounts.balance()
console.log(formatUsd(balance)) // $12.500000
await client.hosting.setPrices('7KQ4-M2XD-4', { base: usdToMicroUsd(0.25) })Stop and wait until gone
await client.sessions.stop(uuid)
await client.sessions.waitStopped(uuid)Errors
Every error extends OctaError; API errors extend OctaApiError with status, message, requestId, retryAfter and rateLimit.
import {
OctaApiError,
OctaAuthenticationError,
OctaRateLimitError,
OctaValidationError,
} from '@octaspace/sdk'
try {
await client.compute.start({ node_number: '7KQ4-M2XD-4', image: 'ubuntu:24.04' })
} catch (err) {
if (err instanceof OctaAuthenticationError) {
// the key is missing, wrong or deleted
} else if (err instanceof OctaValidationError) {
// rejected: err.message says why, for example "Insufficient balance"
} else if (err instanceof OctaRateLimitError) {
// wait err.retryAfter seconds
} else if (err instanceof OctaApiError) {
console.error(`${err.status}: ${err.message} (request ${err.requestId})`)
} else {
throw err
}
}All error classes are listed in Errors and rate limits. GET requests and sessions.stop() are retried on network errors and on 429, 502, 503, 504. Starts, restarts and price changes are never retried.
React
With TanStack Query
npm install @octaspace/sdk @octaspace/sdk-queryimport { computeQueries, sessionQueries, sessionKeys } from '@octaspace/sdk-query'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
const { data: machines } = useQuery(computeQueries.list(client))
// follow a starting session until it is ready
const { data: session } = useQuery({
...sessionQueries.detail(client, uuid),
refetchInterval: (q) => (q.state.data?.status === 'ready' ? false : 3000),
})
// mutations are plain SDK calls; invalidate the keys they affect
const queryClient = useQueryClient()
const stop = useMutation({
mutationFn: (uuid: string) => client.sessions.stop(uuid),
onSuccess: () => queryClient.invalidateQueries({ queryKey: sessionKeys.all() }),
})Keep TanStack's mutation retry at 0 for starts and restarts: they cost money.
Without TanStack Query
npm install @octaspace/sdk @octaspace/sdk-react reactimport { OctaProvider, useComputeMachines } from '@octaspace/sdk-react'
function Machines() {
const { data, loading, error, refetch } = useComputeMachines()
if (loading) return <p>Loading...</p>
if (error) return <p>{error.message}</p>
return <ul>{data?.map((m) => <li key={m.node_number}>{m.node_number}</li>)}</ul>
}
export const App = () => (
<OctaProvider client={client}>
<Machines />
</OctaProvider>
)Each read method has a hook (useBalance, useSessions, useSession(uuid), useHostingNodes, useGpuCurrent...). Every hook takes { enabled, initialData, refetchIntervalMs } and returns { data, error, loading, fetching, refetch }.
More
The repository has detailed guides: configuration, resources, sessions, errors and retries.