# The client library

`@rezincore/client` is a small library for calling your project from an application: accounts and sign-in, rows, files, live updates and functions. It is one file with no dependencies, about 7 KB compressed, and it works in browsers, Node 20 or later, React Native and Expo.

It is a thin layer over the [project API](https://rezincore.com/docs/reference/api.md). Anything it does, you can also do with `fetch`.

## Install

The library is not on a package registry yet. Install it from Rezin Core directly:

```
npm install https://rezincore.com/docs/downloads/rezincore-client.tgz
```

`rezin init` does this for you and writes the set-up file. See the [Expo quickstart](https://rezincore.com/docs/quickstarts/expo.md) and [the others](https://rezincore.com/docs/quickstarts/frameworks.md).

## Create the client

```js
import { createClient } from '@rezincore/client';

export const rezin = createClient({
  url: 'https://api.rezincore.com',
  key: 'rzc_pub_…',            // the project's publishable key
  projectId: 'abcdefghijklmnopqrst', // only needed for sign-in with a provider and public file addresses
});
```

| Option | |
|---|---|
| `url` | The API address |
| `key` | The **publishable** key. A secret key belongs on a server only: never in a browser or a phone app |
| `projectId` | The project ID, for provider sign-in and public file addresses |
| `store` | Where the session is kept between runs. See below |
| `organizationId` | On a server with a secret key: the organization requests act for |
| `fetch`, `WebSocket` | Your own, where the platform's are missing |

### Where the session is kept

Without a `store` the session lives in memory and is gone when the application restarts.

```js
import { createClient, webStore, asyncStore, secureStore } from '@rezincore/client';

createClient({ url, key, store: webStore(localStorage) });              // browser
createClient({ url, key, store: secureStore(SecureStore) });            // Expo: the device keychain
createClient({ url, key, store: asyncStore(AsyncStorage) });            // React Native
```

Any object with `get(key)`, `set(key, value)` and `remove(key)` works; each may be async.

A session is one token. There is nothing to refresh: it stays good while it is used, and ends after the project's idle time (15 minutes unless the project sets less) or its maximum length. When the server says a session has ended, the library forgets it and tells your `onChange` listeners.

## Accounts

```js
await rezin.auth.signUp({ email, password, fullName });   // { confirmationRequired, session }
await rezin.auth.signIn({ email, password });              // add `code` when the account uses an authenticator
await rezin.auth.signOut();

const session = await rezin.auth.session();                // { token, userId, organizationId } or null
const user = await rezin.auth.user();                      // checked with the server; null if signed out
const stop = rezin.auth.onChange((session) => { /* show the right screen */ });
```

| Method | What it does |
|---|---|
| `signUp`, `signIn`, `signOut` | Email and password |
| `signInAnonymously` | A temporary account, where the project allows it |
| `sendSignInLink`, `verifySignInLink` | An emailed link and six-digit code |
| `sendPhoneCode`, `verifyPhoneCode` | A code by text message, where the project has set it up |
| `providerUrl`, `exchangeCode`, `finishProviderSignIn` | Sign-in with Google, GitHub and the other providers |
| `changePassword`, `sendPasswordReset`, `resetPassword` | Passwords |
| `confirmSignUp`, `acceptInvite`, `changeEmail`, `confirmEmailChange` | The emailed links |
| `sendReauthentication`, `verifyReauthentication` | Proving it is still the same person |
| `secondStep.status`, `.start`, `.confirm`, `.off` | The authenticator-app step |

Sign-in with a provider, in a browser:

```js
location.href = rezin.auth.providerUrl('google', { redirectTo: 'https://app.example.com/signed-in' });
// on the page it comes back to:
await rezin.auth.finishProviderSignIn(location.href);
```

The address in `redirectTo` must be on the project's list of allowed addresses.

## Rows

`rezin.table(name)` reads and writes one table through the [data API](https://rezincore.com/docs/database/data-api.md). What comes back is always what the table's [access rules](https://rezincore.com/docs/database/row-level-security.md) allow the signed-in person.

```js
const paid = await rezin.table('orders').select({
  where: { status: 'paid', total: { gte: 50 }, note: { ilike: '*gift*' }, cancelled_at: null },
  columns: ['id', 'total', 'created_at'],
  order: { created_at: 'desc' },
  limit: 20,
});

const one = await rezin.table('orders').first({ where: { id } });          // a row or null
const [made] = await rezin.table('orders').insert({ status: 'new', total: 12 });
const changed = await rezin.table('orders').update({ status: 'paid' }, { where: { id } });
const removed = await rezin.table('orders').delete({ where: { id } });      // how many
```

| In `where` | Means |
|---|---|
| `{ status: 'paid' }` | equals |
| `{ note: null }` | is empty |
| `{ note: { not: null } }` | is not empty |
| `{ total: { gt, gte, lt, lte, neq } }` | comparisons |
| `{ name: { like: 'A*' } }`, `ilike` | text match; `*` stands for anything, `ilike` ignores case |
| `{ id: { in: ['a', 'b'] } }` | one of a list (values without commas) |

`update` and `delete` need a `where` that says something. `limit` is 1 to 1000 and 100 if left out. A `bigint` or `numeric` column comes back as a string.

### Types for your tables

```
rezin types -o src/rezin.types.ts
```

```ts
import type { Tables } from './rezin.types';
const rezin = createClient<Tables>({ url, key });

const rows = await rezin.table('orders').select({ where: { status: 'paid' } });
//    ^ typed as your orders rows; column names and values are checked
```

Run `rezin types` again after the tables change.

## Files

```js
const papers = rezin.files.bucket('papers');

await papers.upload('2026/receipt.pdf', file);                 // a File, Blob, ArrayBuffer or string
const list = await papers.list('2026/');
const response = await papers.download('2026/receipt.pdf');   // then .blob(), .arrayBuffer() or .text()
const { url } = await papers.signedUrl('2026/receipt.pdf', { expiresIn: 600 });
await papers.remove('2026/receipt.pdf');
```

A signed address works without a key until it runs out. `publicUrl(path)` gives the address of a file in a public bucket. See [Storage](https://rezincore.com/docs/storage.md).

## Live updates

```js
const stop = rezin.table('orders').onChange((change) => {
  if (change.op === 'DELETE') remove(change.key);
  else upsert(change.row);                       // 'INSERT' or 'UPDATE'
});
// later
stop();
```

The table must have [live updates switched on](https://rezincore.com/docs/realtime.md). The library opens one connection for all your listeners, signs in again and subscribes again after a drop (waiting longer each time, up to half a minute), and closes when the last listener stops. `rezin.live.status()` is `idle`, `connecting`, `live`, `waiting` or `closed`, and `rezin.live.onStatus(callback)` tells you when it changes.

Changes made while the connection was down are not replayed. After `live` returns, read the rows again if you need to be exact.

## Functions

```js
const { status, data } = await rezin.functions.call('send-welcome', { body: { to: userId } });
```

`body` that is an object is sent as JSON, and the signed-in person's token is sent along. Whatever your function answers is returned as it is, including a status such as 422. Rezin Core's own refusals (a bad key, a limit, the function failing or timing out) are thrown as errors. See [Functions](https://rezincore.com/docs/functions.md).

## Errors

Every failure is a `RezinError`:

```js
import { RezinError } from '@rezincore/client';

try { await rezin.table('orders').insert(row); }
catch (err) {
  if (err instanceof RezinError && err.code === 'not_allowed') {
    // err.status 403, err.message for people, err.requestId for "Why was this refused?"
  }
}
```

| Field | |
|---|---|
| `code` | A stable word. They are listed under [Errors](https://rezincore.com/docs/reference/errors.md) |
| `status` | The HTTP status, or 0 when the server could not be reached (`code` is `network`) |
| `message` | Words for a person |
| `requestId` | For a refusal by a table's access rules: paste it into [Why was this refused?](https://rezincore.com/docs/database/why-refused.md) |

## On a server

```js
const rezin = createClient({ url, key: process.env.REZIN_SECRET_KEY, organizationId });
```

With a secret key and nobody signed in, requests act for the organization you name. Keep the secret key out of browsers, phone apps and their environment files.

## What it does not do

- It does not cache rows or work offline.
- It has no refresh tokens, because sessions do not use them.
- It is not published to a package registry yet; install it from the address above.
- For anything it has no method for, `rezin.request(path, { method, body })` sends the same key and session and throws the same errors.
