> ## 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.

# Client

> The SquareCloudAPI class is the entry point to the SDK. It is instantiated with an API key and exposes every module — applications, databases, workspaces, user and platform service — through a single client.

<Info>
  This page documents **`@squarecloud/api` v5**. If you are upgrading from v4, read the [v4 → v5 migration guide](/en/sdks/js/migrating_to_v5) first. Coming from v3, see the [v3 → v4 migration guide](/en/sdks/js/migrating_to_v4).
</Info>

## Requirements

* **Node.js 20.0.0** or newer
* A valid API key — request one at the [Square Cloud Dashboard](https://squarecloud.app/en/dashboard)

## Installation

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

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

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

## Instantiating the client

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

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

  <Tab title="JavaScript (ESM)">
    ```javascript theme={null}
    import { SquareCloudAPI } from "@squarecloud/api";

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

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

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

### Constructor

| Parameter | Type     | Required | Description                                                               |
| --------- | -------- | -------- | ------------------------------------------------------------------------- |
| `apiKey`  | `string` | Yes      | Your Square Cloud API key. The client will throw if this is not a string. |

## Modules

The client exposes the entire v2 platform through dedicated modules. Each module is a property of the `SquareCloudAPI` instance.

| Property           | Module                                             | Documentation                                             |
| ------------------ | -------------------------------------------------- | --------------------------------------------------------- |
| `api.user`         | Authenticated user, plan, owned apps and databases | This page                                                 |
| `api.applications` | List, fetch, upload and inspect applications       | [Managing applications](/en/sdks/js/managing_application) |
| `api.databases`    | Create, fetch and manage databases                 | [Databases](/en/sdks/js/databases)                        |
| `api.workspaces`   | Create, list and manage workspaces                 | [Workspaces](/en/sdks/js/workspaces)                      |
| `api.service`      | Aggregate platform status                          | This page                                                 |
| `api.cache`        | In-memory cache populated by SDK events            | This page                                                 |

## Getting the authenticated user

`api.user.get()` returns a [`User`](https://github.com/squarecloudofc/sdk-api-js/blob/main/src/structures/user.ts) instance containing the account details, current plan, owned applications and owned databases.

```typescript theme={null}
const user = await api.user.get();

console.log(user.id);          // "abcdef0123456789abcdef01"
console.log(user.name);        // "John Doe"
console.log(user.email);       // "john@example.com"
console.log(user.locale);      // "en-US"
console.log(user.plan.name);   // e.g. "standard"
console.log(user.plan.duration); // plan duration, e.g. "monthly"
console.log(user.plan.memory);   // { limit: 2048, available: 512, used: 1536 } (MB)
console.log(user.createdAt);   // Date

console.log(user.applications); // Collection<string, BaseApplication>
console.log(user.databases);    // Collection<string, Database>
```

`user.applications` and `user.databases` are [`Collection`](https://github.com/squarecloudofc/sdk-api-js/blob/main/src/structures/collection.ts) instances (a `Map` subclass). Iterate them like any `Map`:

```typescript theme={null}
for (const [id, app] of user.applications) {
    console.log(`${app.name} (${id}) — ${app.ram}MB ${app.language}`);
}
```

## Fetching a single application

Use `api.applications.fetch(id)` to retrieve a fully populated `Application` (or `WebsiteApplication`, when the app has a website domain).

```typescript theme={null}
const app = await api.applications.fetch("abc123def456abc123def456");

console.log(app.id, app.name, app.cluster, app.createdAt);

if (app.isWebsite()) {
    // narrowed to WebsiteApplication — `.network` is available
    await app.network.purgeCache();
}
```

The legacy `api.applications.get(id)` overload still exists, but it returns the lighter `BaseApplication` and is only kept for backwards compatibility. **Prefer `.fetch()` for v5.**

## Listing snapshot history (account-wide)

```typescript theme={null}
const appSnapshots = await api.user.snapshots("applications");
const dbSnapshots  = await api.user.snapshots("databases");
```

See [Snapshots](/en/sdks/js/snapshots) for details on snapshot payloads.

## Platform status

`api.service.status()` exposes the aggregated platform health (the same data shown on the public status page).

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

console.log(status.status);  // "ok" | "degraded" | "down"
console.log(status.message); // human-readable summary
```

<Note>
  Unlike most v2 endpoints, this route does **not** wrap its payload in the standard `{ status, response }` envelope.
</Note>

## Client cache

The client maintains an in-memory cache that the SDK keeps in sync as you make calls:

```typescript theme={null}
api.cache.user;   // last fetched User
// each application instance also exposes app.cache.status / .logs / .snapshots
```

The SDK emits typed events you can subscribe to:

```typescript theme={null}
api.on("userUpdate", (previous, current) => {
    console.log("user changed:", current.name);
});

api.on("statusUpdate", (application, previous, current) => {
    console.log(`${application.name} → ${current.status}`);
});

api.on("logsUpdate", (application, previous, current) => {
    console.log(`new logs for ${application.name}`);
});

api.on("snapshotsUpdate", (application, previous, current) => {
    console.log(`${current.length} snapshots for ${application.name}`);
});
```

## Error handling

Failed requests throw a `SquareCloudAPIError`. The error exposes a stable `code` property you can switch on to discriminate failure modes.

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

try {
    const app = await api.applications.fetch("invalid-id");
} catch (err) {
    if (err instanceof SquareCloudAPIError) {
        console.error(err.code);    // e.g. "APP_NOT_FOUND"
        console.error(err.message);
    }
}
```

### Error codes (APIErrorCode)

`APIErrorCode` is a const/union exported by the SDK (re-exported from `@squarecloud/api-types`) listing every value `err.code` can take. v5 renamed several codes for consistency; the old names are kept as **deprecated type aliases**, but the SDK now throws only the new names.

| Old (deprecated alias)          | New                          |
| ------------------------------- | ---------------------------- |
| `ID_INVALID`                    | `INVALID_ID`                 |
| `CODE_INVALID`                  | `INVALID_CODE`               |
| `NAME_INVALID`                  | `INVALID_NAME`               |
| `MEMORY_INVALID`                | `INVALID_MEMORY`             |
| `DATABASE_TYPE_INVALID`         | `INVALID_DATABASE_TYPE`      |
| `DATABASE_VERSION_INVALID`      | `INVALID_DATABASE_VERSION`   |
| `UNKNOWN_WORKSPACE`             | `WORKSPACE_NOT_FOUND`        |
| `UNKNOWN_MEMBER`                | `MEMBER_NOT_FOUND`           |
| `MAX_APPLICATIONS_REACHED`      | `APPLICATIONS_LIMIT_REACHED` |
| `MAX_MEMBERS_REACHED`           | `MEMBERS_LIMIT_REACHED`      |
| `FAILED_WORKSPACE_CREATION`     | `WORKSPACE_CREATION_FAILED`  |
| `FAILED_DATABASE_CREATION`      | `DATABASE_CREATION_FAILED`   |
| `FAILED_CLUSTER_SELECTION`      | `CLUSTER_SELECTION_FAILED`   |
| `FEW_MEMORY`                    | `INSUFFICIENT_MEMORY`        |
| `FAILED_READ`                   | `READ_FAILED`                |
| `FAILED_DELETE`, `DELETE_ERROR` | `DELETE_FAILED`              |
| `FAILED_RENAME`                 | `RENAME_FAILED`              |
| `FAILED_TO_SAVE`                | `SAVE_FAILED`                |
| `FAILED_RESET`                  | `RESET_FAILED`               |
| `FAILED_UPLOAD`                 | `UPLOAD_FAILED`              |
| `FAILED_UPLOAD_DATA`            | `STORAGE_UPLOAD_FAILED`      |
| `COMMIT_ERROR`                  | `COMMIT_FAILED`              |
| `INTERNAL_ERROR`                | `INTERNAL_SERVER_ERROR`      |
| `REGEX_VALIDATION`              | `INVALID_DOMAIN`             |
| `CAN_NOT_SET_SUBDOMAIN`         | `CANNOT_SET_SUBDOMAIN`       |
| `INVALID_APP` (metrics only)    | `METRICS_NOT_SUPPORTED`      |
| `SUBSCRIPTION_REQUIRED`         | `UPGRADE_REQUIRED`           |

Unchanged codes: `KEEP_CALM` (short 429, retry in seconds), `ACCESS_DENIED` (401), `PAYLOAD_TOO_LARGE` (413), `RATE_LIMIT_EXCEEDED`.

New in v5:

| Code                            | Meaning                                                                      |
| ------------------------------- | ---------------------------------------------------------------------------- |
| `DAILY_SNAPSHOTS_LIMIT_REACHED` | 429, the plan's daily snapshot quota was reached (distinct from `KEEP_CALM`) |
| `UPLOAD_ABORTED`                | The client aborted an in-progress upload                                     |
| `LOAD_BALANCER_LIMIT_REACHED`   | 403, attaching a custom domain beyond the plan's app-per-domain limit        |
| `FILE_TOO_LARGE`                | 413, on an upload over 100MB or reading a large file                         |

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

try {
    const snapshots = await api.user.snapshots("applications");
} catch (err) {
    if (err instanceof SquareCloudAPIError) {
        switch (err.code) {
            case "UPGRADE_REQUIRED":
                console.error("an active paid plan is required for account-wide snapshots");
                break;
            default:
                console.error(err.code, err.message);
        }
    }
}
```
