# Orvelt TypeScript SDK

URL: /docs/developers/typescript-sdk

The Orvelt TypeScript SDK (`@orvelt/business`) exposes 12 selected operations from the Business REST API. It is generated from the same contract as the [HTTP API](/docs/api-reference). The [Developer quickstart](/docs/developers) creates a key and sends a first request; this page covers the TypeScript client in detail.

## Install [#install]

Choose your package manager:

**bun**

```bash
bun add @orvelt/business
```

**npm**

```bash
npm install @orvelt/business
```

**pnpm**

```bash
pnpm add @orvelt/business
```

## Functions [#functions]

Operations use the same single-word resource and action names as the API. For example, `link.create` calls `POST /project/{projectId}/link`.

### Resource groups [#resource-groups]

| Group | Functions |
| --- | --- |
| `questions` | `list`, `create`, `update`, `delete` |
| `opinions` | `list` |
| `answers` | `list` |
| `link` | `list`, `create`, `resend` |
| `qr` | `display` |
| `subscribers` | `count`, `invite` |

The [HTTP API reference](/docs/api-reference) also includes endpoints the SDK does not export. The package also exports `orveltEmbed` for the [website embed](/docs/developers/collect/website-embed); browser embed helpers are JavaScript-only.

### Pass parameters as one flat object [#pass-parameters-as-one-flat-object]

Path, query, and body fields all go in one object, never nested under `path`, `query`, or `body`. Every call takes a `projectId`:

```ts
import { opinions } from '@orvelt/business';

const result = await opinions.list({ projectId: 'PROJECT_ID', page: 1, limit: 20 });
```

## Configure the client [#configure-the-client]

### Client options [#client-options]

`orvelt` configures the shared client every function uses. It trims whitespace from the key and throws a `TypeError` if the result is empty, so a missing environment variable fails at startup rather than on the first request.

```ts title="src/orvelt.ts"
import { orvelt } from '@orvelt/business';

orvelt({
  apiKey: process.env.ORVELT_BUSINESS_API_KEY!,
  baseUrl: process.env.ORVELT_API_BASE_URL,
  headers: { 'x-request-id': 'REQUEST_ID' },
});
```

- `baseUrl` targets staging or a local proxy instead of the [production base URL](/docs/developers/authentication#base-url-and-header). Trailing slashes are removed, and relative URLs work for local proxies.
- `fetch` replaces the global `fetch`, for example to add tracing. Bun and Node.js 18 or later provide `fetch` globally; on another runtime, pass your own.
- `headers` are sent with every request.
- `throwOnError: true` makes each call [throw instead of returning `error`](#throw-on-errors).

### Use separate clients [#use-separate-clients]

When one process talks to more than one environment or organization, `createBusinessClient` returns an isolated client and leaves the shared one unchanged. Pass it as the `client` option, the second argument of any operation. Because each client holds its own key, requests for separate organizations never share credentials.

```ts
import { createBusinessClient, opinions } from '@orvelt/business';

const client = createBusinessClient({
  apiKey: process.env.ORVELT_BUSINESS_API_KEY!,
  baseUrl: process.env.ORVELT_API_BASE_URL,
});

const result = await opinions.list({ projectId: 'PROJECT_ID' }, { client });
```

### Bind a project ID [#bind-a-project-id]

`useProject` binds a project ID once and returns the same resource groups without the `projectId` parameter. It is a plain function, not a React hook. You can still pass per-request options, including `client`, as the second argument.

```ts
import { useProject } from '@orvelt/business';

const project = useProject('PROJECT_ID');

const result = await project.opinions.list({
  externalUserId: 'customer-42',
  visibility: 'public',
});
```

## Read results and errors [#read-results-and-errors]

The TypeScript SDK validates successful responses with Zod. Each call resolves to `{ data, error, request, response }`. Exactly one of `data` and `error` is set, and TypeScript narrows `data` once you rule out `error`. `result.response.status` holds the HTTP status. A successful response with an invalid shape returns an error instead of an untyped object.

```ts
import { link } from '@orvelt/business';

const result = await link.create({
  projectId: 'PROJECT_ID',
  customerEmail: 'customer@example.com',
  customerFirstName: 'Alex',
  customerReference: 'ORDER-42',
});

if (result.error) {
  switch (result.response.status) {
    case 401:
      throw new Error('Configure a valid Business API key.');
    case 403:
      throw new Error('The key cannot send delivery links for this project.');
    case 429:
      if (result.error.code === 'LINK_EMAIL_COOLDOWN') {
        return { retryAt: result.error.data.nextEligibleAt };
      }
      throw new Error('Rate limited. Retry with backoff.');
    default:
      throw new Error(result.error.message);
  }
}
```

[Errors](/docs/developers/errors) lists every status and code. Log only the status, error code, and counts you need; keep customer records, opinion text, delivery links, credentials, and raw error objects out of logs.

### Throw on errors [#throw-on-errors]

If your service handles every API failure in one place, set `throwOnError: true`. Each failed call then throws, and `result.data` is always set when the call returns. Keep the default when a caller must react differently to `401`, `403`, `404`, `409`, `429`, or `503`.

```ts
import { orvelt, opinions } from '@orvelt/business';

orvelt({ apiKey: process.env.ORVELT_BUSINESS_API_KEY!, throwOnError: true });

try {
  const result = await opinions.list({ projectId: 'PROJECT_ID' });
  console.log({ count: result.data.opinions.length });
} catch {
  console.error('Business API request failed');
}
```

### Retry transient failures [#retry-transient-failures]

Retry only `429` and `503`, waiting longer after each attempt with random jitter:

```ts
import { opinions } from '@orvelt/business';

const RETRYABLE = new Set([429, 503]);

async function listWithBackoff(projectId: string, attempts = 4) {
  for (let attempt = 0; ; attempt += 1) {
    const result = await opinions.list({ projectId });
    const status = result.response.status;

    if (!result.error || !RETRYABLE.has(status) || attempt === attempts - 1) {
      return result;
    }

    const delay = 1000 * 2 ** attempt + Math.floor(Math.random() * 250);
    await new Promise((resolve) => setTimeout(resolve, delay));
  }
}
```

## Upgrade the SDK [#upgrade-the-sdk]

TypeScript and Python ship together as one SDK release, with shared notes in the [SDK changelog](/changelog?product=sdk). The notes identify each package's changes and versions; breaking changes say what to update. Business app and HTTP API changes are released separately under [Business releases](/changelog?product=business).

### Versions and ranges [#versions-and-ranges]

Versions follow [semantic versioning](https://semver.org): patch releases are fixes only, minor releases add functions or options without breaking existing calls, and major releases contain breaking changes.

```bash
npm install @orvelt/business@latest
```

npm saves a caret range. From `1.0.0`, `^1.2.0` accepts later minor and patch releases of that major version; before `1.0.0`, `^0.2.0` accepts only patch releases of `0.2`. To upgrade only after reading the notes, pin an exact version with `npm install --save-exact @orvelt/business@0.2.0`. Commit your lockfile so every environment runs the same version.

The [UNPKG embed script](/docs/developers/collect/website-embed) always loads the latest release, so embed changes reach your website without a deploy; npm-installed embeds change only when you upgrade the package.