# Node SDK

> Install prosaic-node, set up a client with an API key or OAuth token, and work with pagination, errors and uploads.

Source: https://developer.prosaic.works/docs/sdk/node

`prosaic-node` is the TypeScript and JavaScript client for the Prosaic API. It wraps every public endpoint in a typed method, such as `prosaic.journals.create(...)`, and handles pagination, retries on safe reads, and OAuth.

- Node.js 22 or later
- TypeScript types included
- ESM and CommonJS
- No runtime dependencies

The SDK is in alpha (`0.1.0-alpha.2`) and uses the public contract shipped with that package. The source is at [github.com/prosaichq/prosaic-node](https://github.com/prosaichq/prosaic-node).

## Install

Install the released alpha package:

```sh
yarn add prosaic-node@next
```

The monorepo's `@prosaic/sdk` name is an internal alias. The SDK package version, API `/v1` path and workspace reporting capability are separate. See [Chart of accounts](/docs/ledger/chart-of-accounts) before chart writes. Activated workspaces require explicit reporting assignments; metadata-only patches preserve them.

## Create a client

With an API key, for your own server-side integration:

```ts
import Prosaic from 'prosaic-node';

const apiKey = process.env.PROSAIC_API_KEY;
if (!apiKey) throw new Error('Set PROSAIC_API_KEY first.');

const prosaic = new Prosaic(apiKey);

const { data: me } = await prosaic.me.retrieve();
console.log(`Connected as ${me.name}`);
```

CommonJS code can use `const { Prosaic } = require('prosaic-node')`.

With an OAuth access token, pass a single options object. The second argument is only read when the first is an API key string, so put every option in the object:

```ts
const prosaic = new Prosaic({
  accessToken: tokenProvider, // a string, or a function that returns one
  workspaceId: 'YOUR_WORKSPACE_ID',
});
```

See [OAuth](#oauth) for building `tokenProvider`.

### Options

| Option              | Default                     | Purpose                                                    |
| ------------------- | --------------------------- | ---------------------------------------------------------- |
| `baseUrl`           | `https://app.prosaic.works` | Server origin, without `/api/public/v1`.                   |
| `timeout`           | `30000`                     | Total request deadline in milliseconds, including retries. |
| `maxNetworkRetries` | `2`                         | Retries for transient failures on `GET` and `HEAD`.        |
| `workspaceId`       | Unset                       | Workspace to act in, sent as `x-workspace-id`.             |

Every method takes a final request-options argument that can override `timeout`, `maxNetworkRetries` and `workspaceId` for that call, and take an `AbortSignal` as `signal`:

```ts
const controller = new AbortController();
await prosaic.entities.list(
  {},
  { workspaceId: 'ANOTHER_WORKSPACE_ID', signal: controller.signal },
);
```

`baseUrl` must be HTTPS, except for a loopback address during local development. See [Authentication](/docs/getting-started/authentication) for how workspaces are chosen.

## Methods

Methods are grouped by resource and named for what they do: `list`, `retrieve`, `create`, `update`, `del`, and specific verbs such as `journals.void` or `transactions.reconcile`. Path parameters come first, then the body or query, then request options.

```ts
await prosaic.journals.create(entityId, params);
await prosaic.reports.trialBalance(entityId, { asOfDate: '2026-10-31' });
await prosaic.transactions.reconcile(entityId, transactionId, params);
```

The SDK covers 76 operations in 24 resource groups:

| Area                      | Resources                                                  |
| ------------------------- | ---------------------------------------------------------- |
| Identity and setup        | `me`, `version`, `entities`, `clients`                     |
| Accounts and dimensions   | `charts`, `entityAccounts`, `globalAccounts`, `dimensions` |
| Transactions and journals | `transactions`, `bankAccounts`, `journals`, `changeSets`   |
| Financial reporting       | `ledger`, `generalLedger`, `reports`, `gstReturns`         |
| Contacts and invoices     | `contacts`, `invoices`                                     |
| Assets and files          | `fixedAssets`, `fixedAssetTypes`, `files`                  |
| Automation and extensions | `rules`, `scheduledTasks`, `extensions`                    |

Request and response types are exported under predictable names, such as `JournalsCreateParams`, `EntitiesListResponse` and `ReportsTrialBalanceParams`. The repository's `docs/api-reference.md` lists every method, and the [API reference](/docs/api) documents each endpoint with its SDK method.

## Responses

The SDK keeps the API's response shapes:

- Most methods return a `{ data }` envelope: `const { data: entity } = await prosaic.entities.create(...)`.
- Journal creation, reports and file uploads return the object directly.
- `.withResponse()` on any call also gives you the request ID and the raw `Response`:

```ts
const { data: payload, requestId } = await prosaic.me.retrieve().withResponse();
```

## Pagination

List methods return a promise you can use in three ways:

```ts
// One page, with its envelope.
const page = await prosaic.transactions.list(entityId, { pageSize: 100 });

// Every item, fetching pages as you go.
for await (const transaction of prosaic.transactions.list(entityId, {
  dateFrom: '2026-04-01',
  dateTo: '2026-04-30',
})) {
  console.log(transaction.id, transaction.amount);
}

// At most `limit` items, in an array.
const recent = await prosaic.transactions
  .list(entityId)
  .autoPagingToArray({ limit: 50 });
```

`autoPagingEach(callback)` visits each item and stops fetching when the callback returns `false`. Pagination is not a snapshot: records can change while you iterate.

## Errors

HTTP errors throw `APIError` or a subclass, with the status, the API's error `code`, `details` when the API gives them, and the `requestId`:

```ts
import { APIError, ValidationError } from 'prosaic-node';

try {
  await prosaic.journals.create(entityId, params);
} catch (error) {
  if (error instanceof ValidationError) {
    console.error('Rejected:', error.message, error.details);
  } else if (error instanceof APIError) {
    console.error(error.status, error.code, error.requestId);
  } else {
    throw error;
  }
}
```

| Class                  | When                                      |
| ---------------------- | ----------------------------------------- |
| `ValidationError`      | `400` or `422`                            |
| `AuthenticationError`  | `401`                                     |
| `PermissionError`      | `403`                                     |
| `NotFoundError`        | `404`                                     |
| `ConflictError`        | `409`                                     |
| `RateLimitError`       | `429`                                     |
| `APIError`             | Any other HTTP error, including `5xx`     |
| `ConnectionError`      | The request did not get a response        |
| `TimeoutError`         | The deadline passed (a `ConnectionError`) |
| `InvalidResponseError` | The response could not be read            |
| `OAuthError`           | An OAuth protocol error, with its `code`  |

`error.details` can contain accounting data, so keep it out of public logs. Quote the `requestId` when you report a problem.

### Retries

`GET` and `HEAD` requests are retried on transient failures, up to `maxNetworkRetries` times within the `timeout`, and respect `Retry-After`. **Writes and OAuth token requests are never retried.** The API has no general idempotency key, so after a failed write, check what happened before you try again. [Avoiding double-posting](/docs/ledger/embedded-ledger#avoiding-double-posting) shows one way.

## Uploads

`files.upload(entityId, file)` takes a `File` or `Blob`. Give it a filename, either with a named `File` or with the `filename` request option for a `Blob`, and a content type the API accepts.

```ts
import { readFile } from 'node:fs/promises';

const bytes = await readFile('receipt.pdf');
const { file } = await prosaic.files.upload(
  entityId,
  new File([bytes], 'receipt.pdf', { type: 'application/pdf' }),
);

await prosaic.journals.attachFiles(entityId, logicalJournalId, {
  fileIds: [file.id],
});
```

[Journals](/docs/ledger/journals#attachments) lists the accepted file types and the size limit.

## OAuth

`OAuth` runs the authorization-code flow with S256 PKCE, for public and confidential clients. Register an app first; see [OAuth apps](/docs/apps/oauth-apps).

```ts
import Prosaic, { OAuth } from 'prosaic-node';

const oauth = new OAuth({
  clientId: process.env.PROSAIC_CLIENT_ID!,
  clientSecret: process.env.PROSAIC_CLIENT_SECRET, // leave out for a public client
});

// 1. Start: store `authorization` in the user's server-side session, then
//    redirect their browser to authorization.url.
const authorization = oauth.createAuthorization({
  redirectUri: 'https://your-app.example/oauth/callback',
});

// 2. Callback: checks the redirect and state, then exchanges the code.
const tokens = await oauth.completeAuthorization(callbackUrl, authorization);
await saveTokens(userId, tokens);

// 3. Use: the provider refreshes the access token when it is about to expire.
const prosaic = new Prosaic({
  accessToken: oauth.createTokenProvider(tokens, (updated) =>
    saveTokens(userId, updated),
  ),
});
```

- The default scopes are `openid profile email offline_access`. Pass `scopes` to `createAuthorization` to change them.
- Use each stored authorization once, and expire it quickly.
- Save tokens securely, including `expires_at` and the refresh token. Your save callback must store the updated tokens atomically and return a promise.
- Create one token provider per user grant. If several processes share a grant, coordinate refreshes between them, because refresh tokens rotate.
- An `invalid_grant` error means the user must authorise your app again.
- `refreshToken`, `exchangeCode` and `revokeToken` are there for flows that need them.
- The SDK returns ID tokens unchanged and does not verify them, so do not use them to sign users in to your app.

## Money and dates

- **Amounts.** Keep values exactly as returned. Most amounts are decimal strings; a few endpoints, such as invoices and GST returns, return numbers. Use Decimal.js for arithmetic. Send journal amounts as decimal strings.
- **Dates.** Send calendar dates as `YYYY-MM-DD` strings, and avoid converting them through your machine's timezone.

## For coding agents

The package ships an agent skill at `skills/prosaic-sdk/SKILL.md` that teaches Claude Code and other agents these conventions. See [Build with AI](/docs/ai/build-with-ai) for that and the MCP servers.
