Skip to main content
The @phala/cloud SDK provides a type-safe JavaScript/TypeScript client for the Phala Cloud API. It includes built-in API versioning, Zod schema validation, and comprehensive error handling.

Installation

npm install @phala/cloud
pnpm add @phala/cloud
yarn add @phala/cloud

Quick Start

import { createClient } from "@phala/cloud";

const client = createClient({ apiKey: "phak_your_api_key" });

// Get current user info
const user = await client.getCurrentUser();
console.log(user.user.username);

// List all CVMs
const cvms = await client.getCvmList();
console.log(cvms.items);

Client Creation

createClient(config?)

Creates a full-featured client with all action methods.
import { createClient } from "@phala/cloud";

// Minimal — reads API key from PHALA_CLOUD_API_KEY env var
const client = createClient();
// Explicit configuration
const client = createClient({
  apiKey: "phak_your_api_key",
  baseURL: "https://cloud-api.phala.com/api/v1",
  version: "2026-01-21",
  timeout: 30000,
});

Configuration Options

OptionTypeDefaultDescription
apiKeystringPHALA_CLOUD_API_KEY env varAPI key for authentication
baseURLstringhttps://cloud-api.phala.com/api/v1API base URL (or PHALA_CLOUD_API_PREFIX env var)
versionApiVersion"2026-01-21"API version to use
timeoutnumber30000Request timeout in milliseconds
useCookieAuthbooleanfalseUse cookie-based auth instead of API key
headersRecord<string, string>Additional request headers
onResponseErrorfunctionCustom response error handler

Tree-Shaking with createBaseClient

For smaller bundles, use createBaseClient with individual action imports:
import { createBaseClient, getCurrentUser, getCvmList } from "@phala/cloud";

const client = createBaseClient({ apiKey: "phak_your_api_key" });

// Call actions as standalone functions
const user = await getCurrentUser(client);
const cvms = await getCvmList(client);

Extending the Base Client

createClient already includes all built-in actions as methods. The .extend() method on createBaseClient is useful when you want to selectively include actions (for tree-shaking) or add your own custom actions:
import { createBaseClient, getCurrentUser, getCvmList } from "@phala/cloud";

const client = createBaseClient({ apiKey: "phak_your_api_key" }).extend({
  getCurrentUser,
  getCvmList,
});

// Only the actions you included are available as methods
const user = await client.getCurrentUser();

Available Actions

Actions marked with V return different response types depending on the client’s API version.

Authentication & User

MethodDescription
getCurrentUser() VGet current user, workspace, and credits info

CVM Query

MethodDescription
getCvmList(request?) VList all CVMs (paginated)
getCvmInfo(request) VGet single CVM details
getCvmStats(request)Get CVM system stats
getCvmNetwork(request)Get CVM network info
getCvmState(request)Get CVM current state
getCvmDockerCompose(request)Get Docker Compose config
getCvmComposeFile(request)Get compose file content
getCvmContainersStats(request)Get container stats
getCvmAttestation(request)Get TEE attestation
getCvmPreLaunchScript(request)Get pre-launch script
getCvmStatusBatch(request)Get status of multiple CVMs
getCvmUserConfig(request)Get user-level CVM config
checkCvmIsAllowed(request)Check on-chain deployment allowance

CVM Lifecycle

MethodDescription
provisionCvm(request)Create a new CVM
commitCvmProvision(request)Commit a CVM provision
startCvm(request)Start a CVM
stopCvm(request)Stop a CVM
shutdownCvm(request)Shutdown a CVM
restartCvm(request)Restart a CVM
deleteCvm(request)Delete a CVM
replicateCvm(request)Create a copy of a CVM
watchCvmState(request)Watch CVM state changes via SSE

CVM Configuration

MethodDescription
updateCvmEnvs(request)Update environment variables
updateDockerCompose(request)Update Docker Compose config
updatePreLaunchScript(request)Update pre-launch script
updateCvmResources(request)Update resource allocation
updateCvmVisibility(request)Update visibility settings
updateOsImage(request)Update OS image
getAvailableOsImages(request?)List available OS images
provisionCvmComposeFileUpdate(request)Provision a compose file update
commitCvmComposeFileUpdate(request)Commit a compose file update
patchCvm(request)Unified partial CVM update
confirmCvmPatch(request)Confirm on-chain KMS patch (Phase 2)
commitCvmUpdate(request)Commit update with token (multisig)
refreshCvmInstanceId(request)Refresh a CVM instance ID
refreshCvmInstanceIds(request)Batch refresh CVM instance IDs

Apps

MethodDescription
getAppList(request?) VList apps
getAppInfo(request) VGet app details
getAppCvms(request) VList CVMs for an app
getAppRevisions(request)List app revision history
getAppRevisionDetail(request)Get app revision details
getAppFilterOptions()Get available filter options for app list
getAppAttestation(request)Get app TEE attestation
getAppDeviceAllowlist(request)Get app device allowlist status
checkAppIsAllowed(request)Check on-chain app allowance
checkAppCvmsIsAllowed(request)Batch check app CVMs allowance

Workspace

MethodDescription
listWorkspaces(request?)List workspaces
getWorkspace(request)Get workspace details
getWorkspaceNodes(request)Get workspace nodes
getWorkspaceQuotas(request)Get workspace resource quotas

Nodes, Instance Types & OS Images

MethodDescription
getAvailableNodes()List available TEE nodes
listAllInstanceTypeFamilies()List all instance type families
listFamilyInstanceTypes(request)List instance types in a family
getOsImages(request?)List public OS images (paginated)

KMS (Key Management)

MethodDescription
getKmsInfo(request)Get KMS info
getKmsList(request?)List KMS instances
getKmsOnChainDetail(request)Get on-chain KMS details
getAppEnvEncryptPubKey(request)Get env encryption public key
nextAppIds(request?)Get next available app IDs

SSH Keys

MethodDescription
listSshKeys()List SSH keys
createSshKey(request)Add an SSH key
deleteSshKey(request)Remove an SSH key
importGithubProfileSshKeys(request)Import SSH keys from GitHub profile
syncGithubSshKeys()Sync SSH keys from GitHub

On-Chain Contract Actions

These functions interact directly with the blockchain, not the Phala Cloud API. They require ETH for gas (write operations) or a public client (read operations).
MethodDescription
deployAppAuth(request)Deploy an AppAuth smart contract
addComposeHash(request)Register a compose hash on-chain
addDevice(request)Add a device to the on-chain allowlist
removeDevice(request)Remove a device from the on-chain allowlist
setAllowAnyDevice(request)Toggle the allow-any-device flag
getAllowedDevices(request)Query the on-chain device allowlist
checkDeviceAllowed(request)Check if a device is allowed on-chain
checkComposeHashAllowed(request)Check if a compose hash is allowed on-chain
checkOnChainPrerequisites(request)Batch check all on-chain prerequisites

Safe Methods

Every action has a safe variant that returns a SafeResult instead of throwing:
const result = await client.safeGetCvmInfo({ id: "cvm-abc123" });

if (result.success) {
  console.log(result.data);
} else {
  console.error(result.error.message);
}
The SafeResult type:
type SafeResult<T, E = SafeError> =
  | { success: true; data: T; error?: never }
  | { success: false; data?: never; error: E };

Custom Schema Validation

Every action accepts an optional schema parameter for custom response validation. For actions without required request parameters, pass schema as the first argument:
import { z } from "zod";

const MySchema = z.object({ username: z.string() });
const user = await client.getCurrentUser({ schema: MySchema });
// user is typed as { username: string }

// Disable validation (returns unknown)
const raw = await client.getCurrentUser({ schema: false });
For actions with required request parameters, pass schema as the second argument:
const MyCvmSchema = z.object({ id: z.string(), name: z.string() });
const cvm = await client.getCvmInfo({ id: "cvm-abc123" }, { schema: MyCvmSchema });

Event Handling

Listen for error events across all API calls:
client.on("error", (error) => {
  console.error("API Error:", error.message);
});

// Listen once
client.once("error", (error) => {
  console.error("First error:", error.message);
});

// Remove listener
client.off("error", handler);

Debug Logging

Enable detailed cURL-format request/response logging:
DEBUG=phala::api-client node your-script.js

Environment Variables

VariableDescription
PHALA_CLOUD_API_KEYAPI key for authentication
PHALA_CLOUD_API_PREFIXBase URL for the API

Webhook Signature Verification

The SDK provides utilities for verifying webhook signatures, exported from a separate subpath to avoid bundling node:crypto into browser builds:
import { verifyWebhookSignature, parseWebhookEvent } from "@phala/cloud/webhook";

// Verify a single signature
const isValid = verifyWebhookSignature({
  secret: "whsec_...",
  timestamp: req.headers["x-webhook-timestamp"],
  body: rawBody,
  signature: req.headers["x-webhook-signature"],
});

// Or parse and verify in one step
const event = parseWebhookEvent({
  headers: req.headers,
  body: rawBody,
  secret: "whsec_...",
});
See Webhooks for full payload format and delivery behavior.