> ## Documentation Index
> Fetch the complete documentation index at: https://docs.squarecloud.app/llms.txt
> Use this file to discover all available pages before exploring further.

# JavaScript SDK: quickstart and client

> Install the Square Cloud JavaScript SDK (@squarecloud/api v6), create a client with your API key and follow its conventions: ids, workspace apps and timeouts.

<Info>
  This page documents **`@squarecloud/api` v6**, a rewrite of the SDK. Coming from v5? Read the [v5 → v6 migration guide](/en/sdks/js/migrating_to_v6).
</Info>

## Requirements

* **Node.js 22** or newer, **Deno**, **Bun** or an edge runtime. The SDK only needs `fetch`, `FormData`, `Blob` and web streams.
* An API key (see [API key and scopes](#api-key-and-scopes)).

The package ships ESM and CommonJS builds, has **no runtime dependencies** and includes its own TypeScript types: you no longer need `@squarecloud/api-types`.

## Installation

<Tabs>
  <Tab title="npm">
    ```bash theme={"system"}
    npm install @squarecloud/api
    ```
  </Tab>

  <Tab title="pnpm">
    ```bash theme={"system"}
    pnpm add @squarecloud/api
    ```
  </Tab>

  <Tab title="yarn">
    ```bash theme={"system"}
    yarn add @squarecloud/api
    ```
  </Tab>

  <Tab title="bun">
    ```bash theme={"system"}
    bun add @squarecloud/api
    ```
  </Tab>

  <Tab title="deno">
    ```bash theme={"system"}
    deno add npm:@squarecloud/api
    ```
  </Tab>
</Tabs>

## API key and scopes

Create a key at [squarecloud.app/account/security](https://squarecloud.app/en/account/security). The SDK sends it as-is in the `Authorization` header (no `Bearer` prefix).

A key can be limited to **scopes** (`apps:read`, `apps:deploy`, `apps:control`, `ai:chat`, ...) and to specific apps or databases:

* A call outside those limits throws a [`SquareCloudAPIError`](/en/sdks/js/errors) with 403 `MISSING_SCOPE` or `RESOURCE_NOT_ALLOWED`.
* List methods (`account.me()`, `apps.statusAll()`, ...) only return the resources the key can see.
* An unknown, revoked or expired key is 401 `ACCESS_DENIED`.

<Warning>
  Keep the key on the server. The SDK runs in a browser too, but that would expose the key to every visitor.
</Warning>

The examples read the key from the `SQUARECLOUD_API_KEY` environment variable. Set it in the terminal where you run them:

<Tabs>
  <Tab title="macOS / Linux">
    ```bash theme={"system"}
    export SQUARECLOUD_API_KEY="your-api-key"
    ```
  </Tab>

  <Tab title="Windows (PowerShell)">
    ```powershell theme={"system"}
    $env:SQUARECLOUD_API_KEY = "your-api-key"
    ```
  </Tab>
</Tabs>

## Creating the client

<Tabs>
  <Tab title="TypeScript / ESM">
    ```typescript theme={"system"}
    import { SquareCloudAPI } from "@squarecloud/api";

    const api = new SquareCloudAPI(process.env.SQUARECLOUD_API_KEY!);

    const { user, applications } = await api.account.me();
    console.log(`Hi ${user.name}, you have ${applications.length} apps`);
    ```
  </Tab>

  <Tab title="CommonJS">
    ```javascript theme={"system"}
    const { SquareCloudAPI } = require("@squarecloud/api");

    const api = new SquareCloudAPI(process.env.SQUARECLOUD_API_KEY);
    ```
  </Tab>
</Tabs>

The first example prints your account name and the number of apps the key can see:

```text theme={"system"}
Hi Jane, you have 3 apps
```

An empty or whitespace-only key throws a `TypeError` in the constructor, before any request.

### Options

```typescript theme={"system"}
import { BASE_URL, SquareCloudAPI } from "@squarecloud/api";

const api = new SquareCloudAPI(process.env.SQUARECLOUD_API_KEY!, {
    baseUrl: BASE_URL, // "https://api.squarecloud.app/v2" (default)
    timeoutMs: 30_000,
    maxRetries: 2,
    userAgent: "my-bot/1.0",
    fetch, // any fetch-compatible function (proxy, tracing, tests)
});
```

| Option | Default | Description |
| - | - | - |
| `baseUrl` | `https://api.squarecloud.app/v2` | API base URL. A trailing `/` is stripped. Also exported as `BASE_URL`. |
| `timeoutMs` | `30000` | Timeout **per attempt**, covering the whole response. See [Timeouts](#timeouts). |
| `maxRetries` | `2` | Retries of safe failures only (up to 3 attempts). A negative value counts as `0`. See [Retries](/en/sdks/js/errors#retries). |
| `userAgent` | `squarecloud-sdk-js/<version>` | Replaces the whole `User-Agent` header. |
| `fetch` | the global `fetch` | A custom `fetch` for proxies, tracing or tests. |

<Warning>
  The API key is stored as a regular property of the client object. Don't `console.log` or serialize the client.
</Warning>

## Modules

| Property | Covers | Page |
| - | - | - |
| `api.account` | `me()`, `snapshots({ scope })` | [Account](#account) and [Snapshots](/en/sdks/js/snapshots) |
| `api.service` | `status()` | [Platform status](#platform-status) |
| `api.apps` | Get, delete, status, lifecycle, logs, metrics, domains, load balancers | [Managing applications](/en/sdks/js/managing_application) |
| `api.apps.create` / `commit` | Uploads | [Commit and upload](/en/sdks/js/commit_and_upload) |
| `api.apps.files` | File manager | [Managing files](/en/sdks/js/managing_files) |
| `api.apps.envs` | Environment variables | [Environment variables](/en/sdks/js/environment_variables) |
| `api.apps.deploys` | Webhook and GitHub App deploys | [Deploys](/en/sdks/js/deploys) |
| `api.apps.network` | Analytics, logs, DNS, custom domain, cache | [Network](/en/sdks/js/network) |
| `api.apps.realtime` | Live logs and status | [Realtime](/en/sdks/js/realtime) |
| `api.apps.snapshots` / `api.databases.snapshots` / `api.downloadSnapshot` | Backups | [Snapshots](/en/sdks/js/snapshots) |
| `api.databases` | Managed databases | [Databases](/en/sdks/js/databases) |
| `api.workspaces` | Workspaces, members and shared apps | [Workspaces](/en/sdks/js/workspaces) |
| `api.ai` | `chat()` | [AI](/en/sdks/js/ai) |

The only runtime exports are `SquareCloudAPI`, `SquareCloudAPIError` and `BASE_URL`. Every other export (`App`, `RuntimeStats`, `ErrorCode`, ...) is a type:

```typescript theme={"system"}
import type { App, Snapshot } from "@squarecloud/api";
```

## Conventions

### Ids first, plain data back

Every method takes the resource id as its first argument and returns **plain data** (no classes, no cache). Field names are the API's own (`created_at`, `version_id`, `lastModified`, `joinedAt`, `netIO`, ...), so the [API reference](/en/api-reference/authentication) applies as-is.

* Mutations resolve to `void`, unless the API returns data (`envs.*`, `deploys.setWebhook`, `deploys.linkGithubApp`, `databases.resetCredentials` and the `create` methods).
* A string result is never `undefined`: it is `""` when the API sends none.
* Lists come complete in one call: there is no pagination.

Methods are arrow functions, so you can destructure them:

```typescript theme={"system"}
const { restart, logs } = api.apps;

await restart(appId);
console.log(await logs(appId));
```

### Workspace apps

Every `appId` also accepts the composite form `<appId>-<workspaceId>` to act on an app shared with you through a [workspace](/en/sdks/js/workspaces). `workspaces.get()` and `workspaces.list()` return raw ids; you build the composite id yourself:

```typescript theme={"system"}
await api.apps.restart(`${appId}-${workspaceId}`);
```

### Ids are encoded

Ids in the URL path are percent-encoded. An id that is empty, `.` or `..` would reach a different route, so it fails locally with `INVALID_ID` (status `0`) before anything is sent. Workspace routes send their ids in the body instead: there, `INVALID_ID` (400) comes from the server.

### Dates

`start` and `end` arguments (see [Network](/en/sdks/js/network)) take an ISO 8601 string or a `Date`. Dates in responses stay as the API sends them (ISO strings, or Unix milliseconds where the API uses them).

## Timeouts

| Call | Timeout |
| - | - |
| Every other call | `timeoutMs` (30 s) per attempt |
| Calls the server holds open: `start`/`stop`/`restart` of apps, `start`/`stop` of databases, `databases.create`, snapshot `create`/`restore`, `ai.chat` | At least **120 s** (a larger `timeoutMs` wins) |
| Uploads (`apps.create`, `apps.commit`), `files.write` above 1 MiB, `downloadSnapshot` | None: pass a `signal` to cancel |
| `apps.realtime` | Only until the response headers arrive |

A `timeoutMs` of `0` or less, `Infinity` or `>= 2^31` disables **every** timeout, the 120 s floors included.

Only five methods take an `AbortSignal`: `apps.create`, `apps.commit`, `files.write`, `apps.realtime` and `downloadSnapshot`.

```typescript theme={"system"}
const controller = new AbortController();
setTimeout(() => controller.abort(), 60_000);

await api.apps.commit(appId, "./build.zip", { signal: controller.signal });
```

An aborted call rejects with the signal's `reason`, not with a `SquareCloudAPIError`. An aborted `realtime()` loop just ends.

## Account

`api.account.me()` returns the authenticated user plus the apps and databases the key can see.

```typescript theme={"system"}
const { user, applications, databases } = await api.account.me();

console.log(user.id, user.name, user.email, user.plan.name);
console.log(user.plan.memory); // { limit, available, used } in MB
console.log(user.plan.duration ? new Date(user.plan.duration) : "never expires");
```

| Field | Description |
| - | - |
| `user` | `id`, `name`, `email`, `locale`, `created_at` and `plan` (`name`, `memory`, `duration`: the Unix ms at which the plan **expires**, `null` if it never does) |
| `applications` | Array of `{ id, name, desc?, ram, lang, domain?, custom?, cluster, created_at }` |
| `databases` | Array of `{ id, name, ram, type, cluster, created_at }` |

`api.account.snapshots({ scope })` lists every snapshot of the account: see [Snapshots](/en/sdks/js/snapshots#account-snapshots).

## Platform status

`api.service.status()` returns the public platform status. The route needs no valid key, but the client still requires a non-empty one.

```typescript theme={"system"}
const status = await api.service.status();

console.log(status.status); // "online" | "degraded" | "unknown"
console.log(status.message);

for (const [name, service] of Object.entries(status.services ?? {})) {
    console.log(name, service.status); // "operational" | "degraded" | "outage" | "maintenance" | "unknown"
}
```

`unknown` means the check itself could not run: it is not evidence of an outage.

## Next steps

<CardGroup cols={2}>
  <Card title="Managing applications" icon="server" href="/en/sdks/js/managing_application">
    Status, lifecycle, logs and metrics.
  </Card>

  <Card title="Errors" icon="triangle-exclamation" href="/en/sdks/js/errors">
    Error class, retries and rate limits.
  </Card>

  <Card title="API introduction" icon="code" href="/en/api-reference/introduction">
    Base URL, authentication and a first request.
  </Card>

  <Card title="CLI quickstart" icon="terminal" href="/en/cli-reference/quickstart">
    Deploy and manage apps from the terminal.
  </Card>
</CardGroup>


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.