# TypeScript and Node.js
Source: https://www.desktopaccountingapi.com/docs/sdks/typescript/

> Install and use the Desktop Accounting API TypeScript SDK, with typed resources, auto-pagination, typed errors and safe retries.

```sh
npm install @desktopaccountingapi/quickbooks-desktop@0.12.1
```

Requires Node.js 20 or newer, or another runtime with `fetch` and WebCrypto, such as Deno, Bun or Cloudflare Workers. The package ships ES module and CommonJS builds with type declarations and has no runtime dependencies.

## Create a client

```ts
import { DesktopAccountingApi } from "@desktopaccountingapi/quickbooks-desktop";

const client = new DesktopAccountingApi({
  apiKey: process.env.DAAPI_SECRET_KEY, // the default, so this line is optional
  timeout: 100_000, // milliseconds
  maxRetries: 2,
});

// Scope a client to one end user for QuickBooks calls
const qb = client.forEndUser("eu_01j9x4m6v4c8k2t7q0r5s3w1zb");
```

`forEndUser` returns a new client with the same options; it is cheap, so create one per request or per customer.

## Make calls

The resource tree mirrors the API reference: `client.endUsers`, `client.authSessions`, `client.requests` and `client.qbd.<resource>`.

```ts
import { DesktopAccountingApi } from "@desktopaccountingapi/quickbooks-desktop";

const qb = new DesktopAccountingApi().forEndUser("eu_01j9...");

const customer = await qb.qbd.customers.create({ name: "Northwind Traders", email: "ap@northwind.example" });

const invoice = await qb.qbd.invoices.create({
  customerId: customer.id,
  transactionDate: "2026-10-05",
  lines: [{ itemId: "80000003-1730311000", quantity: 2, rate: "125.00" }],
});

await qb.qbd.invoices.update(invoice.id, { revisionNumber: invoice.revisionNumber, memo: "Thanks for your order" });

const report = await qb.qbd.reports.aging({ reportType: "ar_aging_summary" });
console.log(report.title);
```

Money fields are decimal strings (`"125.00"`). Use a decimal library such as `decimal.js` or `big.js` for arithmetic, never `Number`.

Per-call options go in the last argument:

```ts
import { DesktopAccountingApi } from "@desktopaccountingapi/quickbooks-desktop";

const client = new DesktopAccountingApi();
await client.qbd.invoices.retrieve("1A4F-1730312567", { endUserId: "eu_01j9...", timeout: 30_000 });
```

## Pagination

List methods return a `PagePromise`. Await it for the first page, iterate it for every item, or call `.pages()` for page by page.

```ts
import { DesktopAccountingApi } from "@desktopaccountingapi/quickbooks-desktop";

const qb = new DesktopAccountingApi().forEndUser("eu_01j9...");

const first = await qb.qbd.invoices.list({ limit: 50 });
console.log(first.data.length, first.hasMore, first.cursorExpiresAt);

for await (const invoice of qb.qbd.invoices.list({ updatedAfter: "2026-10-01" })) {
  console.log(invoice.refNumber);
}

const allVendors = await qb.qbd.vendors.list().listAll();
console.log(allVendors.length);
```

Fast item loops request the next page when they reach it. If you keep requesting items after holding a page for more than two seconds, the iterator can fetch the next page early to reduce cursor expiry. A later `break` can leave that page unused. Page-by-page iteration fetches a page only when requested, so fetch the next page promptly. Read-ahead cannot keep a cursor alive while your code pauses indefinitely. If the cursor expires mid-iteration, the iterator throws `CursorExpiredError` with `itemsYielded`, `pagesServed`, `lastId`, `lastUpdatedAt` and `reason`, and does not restart the list. See [Pagination](https://www.desktopaccountingapi.com/docs/guides/pagination/).

## Errors

Every API error is an `ApiError` subclass: `InvalidRequestError`, `AuthenticationError`, `PermissionError`, `BillingError`, `RateLimitError`, `IntegrationConnectionError`, `IntegrationError`, `OutcomeUnknownError`, `InternalError`, plus `CursorExpiredError` and `ResultUnavailableError` (the result is no longer available: never send an applied write again, read the object instead; a read is safe to send again). Network failures with no response throw `ApiConnectionError` (`ApiTimeoutError` for a client timeout). `RequestPendingError` means the SDK stopped waiting for a request that reached QuickBooks: the client timeout ended, or checking on it failed (the failed check says nothing about the write). Its `requestId` lets you read the result later, `timeoutError` is the original 504 and `idempotencyKey` the key to resend with. Every error of a write carries `idempotencyKey`.

```ts
import { DesktopAccountingApi, ApiError, IntegrationConnectionError } from "@desktopaccountingapi/quickbooks-desktop";

const qb = new DesktopAccountingApi().forEndUser("eu_01j9...");
try {
  await qb.qbd.healthCheck();
} catch (err) {
  if (err instanceof IntegrationConnectionError) console.warn(err.userFacingMessage);
  else if (err instanceof ApiError) console.error(err.code, err.requestId, err.message);
  else throw err;
}
```

See [Error handling](https://www.desktopaccountingapi.com/docs/guides/error-handling/).

## Idempotency and retries

Writes get an `Idempotency-Key` automatically, reused across retries. Pass `idempotencyKey` in the options to tie a write to your own record. Retries follow `Daapi-Should-Retry` and never repeat a write with an unknown or pending outcome. See [Idempotency](https://www.desktopaccountingapi.com/docs/guides/idempotency/).

## Raw responses

Add `.withResponse()` to a call to get the HTTP response and request ID along with the data:

```ts
import { DesktopAccountingApi } from "@desktopaccountingapi/quickbooks-desktop";

const qb = new DesktopAccountingApi().forEndUser("eu_01j9...");

const { data, response, requestId } = await qb.qbd.customers.retrieve("80000001-1730311000").withResponse();
console.log(data.name, requestId, response.headers.get("daapi-warnings"));
```

## Logging

Pass a `logger` with `debug` and `warn` methods (`console` works) to see each attempt's method, path, status, request ID, attempt number and duration, and `logLevel` (`debug`, `info`, `warn`, `error` or `off`) to filter it. Setting `logLevel` or the `DAAPI_LOG` environment variable without a logger logs to `console`. The SDK never passes the logger the API key, headers or bodies.

## Async requests

Pass `{ async: true }` to queue a request without waiting. The call returns a `RequestHandle`:

```ts
import { DesktopAccountingApi } from "@desktopaccountingapi/quickbooks-desktop";

const qb = new DesktopAccountingApi().forEndUser("eu_01j9...");

const handle = await qb.qbd.invoices.create(
  { customerId: "80000001-1730311000", lines: [{ itemId: "80000003-1730311000", quantity: 2, rate: "125.00" }] },
  { async: true, queueTtl: 3600 },
);
console.log(handle.id); // req_...
const invoice = await handle.wait({ timeout: 120_000 }); // long-polls until QuickBooks answers
console.log(invoice.refNumber);
```

`handle.status()` reads the request once, and `handle.result()` returns the result if the request has finished or throws `RequestPendingError` if it has not. A write the API [recovered](https://www.desktopaccountingapi.com/docs/guides/request-lifecycle/#recovered-writes) without its result throws `ResultUnavailableError` from `wait()` and `result()`: do not send it again; retrieve the object by `err.recoveredObjectId`. Use [webhooks](https://www.desktopaccountingapi.com/docs/guides/webhooks/) instead of waiting for large batches.

## Webhooks

```ts
import { DesktopAccountingApi, WebhookVerificationError } from "@desktopaccountingapi/quickbooks-desktop";

const client = new DesktopAccountingApi();

export async function handleWebhook(rawBody: string, headers: Headers): Promise<number> {
  try {
    const event = await client.webhooks.verify(rawBody, headers, process.env.DAAPI_WEBHOOK_SECRET!);
    console.log(event.type, event.data["id"]);
    return 204;
  } catch (err) {
    if (err instanceof WebhookVerificationError) return 400;
    throw err;
  }
}
```

`verify` is async. It checks the signature and timestamp against the raw body and returns the typed event, or throws `WebhookVerificationError`. `verifyWebhook(...)` is the same function without a client.

## Porting from Conductor

Code written for `conductor-node` runs after you change the import and the API key, pass the new `eu_...` end-user IDs, and make the changes listed below the example. Keys, end users and customer reconnection come first; see [Migrating from Conductor](https://www.desktopaccountingapi.com/docs/get-started/migrating-from-conductor/).

```ts
// Before:
//   import Conductor from "conductor-node";
//   const conductor = new Conductor({ apiKey: process.env.CONDUCTOR_SECRET_KEY });
import Conductor, { NotFoundError } from "@desktopaccountingapi/quickbooks-desktop";

const conductor = new Conductor({ apiKey: process.env.DAAPI_SECRET_KEY });

// Unchanged Conductor code:
const endUserId = "eu_01j9...";
for await (const invoice of conductor.qbd.invoices.list({ conductorEndUserId: endUserId, limit: 50 })) {
  console.log(invoice.refNumber);
}
try {
  await conductor.qbd.invoices.retrieve("1A4F-1730312567", { conductorEndUserId: endUserId });
} catch (err) {
  if (err instanceof NotFoundError) console.log("No such invoice");
  else if (err instanceof Conductor.APIError) console.log(err.status, err.error?.error?.code, err.error?.error?.userFacingMessage);
  else throw err;
}
```

- `conductorEndUserId` is accepted in the params of QuickBooks Desktop calls and in the call options, and sent as `Daapi-End-User-Id`. Passing a different `endUserId` too throws.
- `baseURL`, `timeout` (per attempt), `maxRetries`, `defaultHeaders`, `fetch`, `fetchOptions`, `logger` and `logLevel` keep their names. A base URL ending in `/v1` works.
- `ConductorError`, `APIError`, `APIConnectionError`, `APIConnectionTimeoutError`, `APIUserAbortError`, `AuthenticationError`, `PermissionDeniedError` and `RateLimitError` exist under those names, and `BadRequestError`, `NotFoundError`, `ConflictError`, `UnprocessableEntityError` and `InternalServerError` match by HTTP status. `err.error.error` is the error object, as Conductor's documentation unwraps it, and every field (`code`, `type`, `userFacingMessage`, `integrationCode`, `requestId`, `httpStatusCode`) is also on the error itself, next to `errorCause`, `fixes`, `docsUrl` and `outcome`.
- Replace `page.hasNextPage()` / `getNextPage()` loops with `for await` or `.pages()`.
