# JavaScript: install and configure
Source: https://sovaria.in/docs/javascript-setup

Install @sovaria/sdk, where it runs, create a client for browsers and for servers, every configuration option, sessions, retries and idempotency, errors and their codes, and fixes for common setup problems.

## Install

npm:
```bash
npm install @sovaria/sdk
```

pnpm:
```bash
pnpm add @sovaria/sdk
```

yarn:
```bash
yarn add @sovaria/sdk
```

| Runs in | Notes |
|---|---|
| Browsers | Modern evergreen browsers. Sessions (access and refresh token) persist in `localStorage` by default, as with Supabase and Firebase: any script that runs on your page could read them, so keep a strict Content-Security-Policy, or pass `persistSession: { storage }` to keep them elsewhere (or `false` for memory only). |
| Node.js | Any version with global `fetch` (18+). Pass `fetchImpl` to use another implementation. |
| Deno, Bun, edge runtimes | Uses the global `fetch` and Web Crypto. |
| React Native | `persistSession: { storage }` takes a synchronous store (`getItem`, `setItem`, `removeItem` — for example MMKV). With an async store such as AsyncStorage, save tokens from `onTokenRefreshSensitive` and restore them with `setAccessToken` / `setRefreshToken` ([Sign-in for mobile apps](https://sovaria.in/docs/mobile-auth)). |

## Create a client

Browser / app:
```ts
import { createClient } from '@sovaria/sdk'

export const sovaria = createClient(
  import.meta.env.VITE_SOVARIA_URL,        // https://<project-ref>.sovarias.in
  import.meta.env.VITE_SOVARIA_ANON_KEY,
)
```

Server (service key):
```ts
import { createClient } from '@sovaria/sdk'

// Backends, CI and functions only — this key bypasses row-level security and the default rules.
const admin = createClient(process.env.SOVARIA_URL!, process.env.SOVARIA_SERVICE_ROLE_KEY!)
```

Server, as a user:
```ts
import { createClient } from '@sovaria/sdk'

// One client per request, acting as the signed-in user who called your API.
export function clientFor(accessToken: string) {
  return createClient(process.env.SOVARIA_URL!, process.env.SOVARIA_ANON_KEY!, { persistSession: false })
    .setAccessToken(accessToken)
}
```

From sovaria.config.json:
```ts
import config from './sovaria.config.json'          // written by `sov link`
import { createClientFromProjectConfig } from '@sovaria/sdk'

export const sovaria = createClientFromProjectConfig(config, { anonKey: import.meta.env.VITE_SOVARIA_ANON_KEY })
```

One client per app (or per request on a server acting for users). The URL names the project, so no ids are needed. Which key goes where: [Connect your app](https://sovaria.in/docs/connect-your-app); variable names: [Environment variables](https://sovaria.in/docs/environment-variables).

## supabase-js style results and typed clients

Pass `results: 'supabase'` and every awaited call resolves to `{ data, error }` (tables also `count` and `status`) and never rejects, as in supabase-js — code written for supabase-js runs as it is ([supabase-js code on Sovaria](https://sovaria.in/docs/supabase-to-sovaria)). Generate your schema's types with `sov gen types typescript > src/database.types.ts` and pass them as `createClient<Database>()`: `from('books')` then knows the row, insert and update types, and `rpc('fn', args)` its arguments and result. The CLI writes supabase's `Database` shape (`Tables`, `Views`, `Functions`, `Enums`), so types generated for supabase also fit.

TypeScript:
```ts
import { createClient } from '@sovaria/sdk'
import type { Database, Tables } from './database.types'

export const sovaria = createClient<Database>(import.meta.env.VITE_SOVARIA_URL, import.meta.env.VITE_SOVARIA_ANON_KEY, { results: 'supabase' })

const { data: books, error } = await sovaria.from('books').select('*').eq('genre', 'sci-fi')   // Tables<'books'>[] | null
await sovaria.from('books').insert({ title: 'Dune' })                                          // TablesInsert<'books'>
const { data: n } = await sovaria.rpc('count_books', { owner: userId })                        // number | null
const { data: top } = await sovaria.rpc('top_books', { days: 7 }).order('score', { ascending: false }).limit(5)
```

`rpc(fn, args, { get, head, count })` calls a Postgres function; one that returns rows takes filters, `order`, `range`, `single()` like a table read. App users need a policy that allows `fn:<name>` ([Row-level security and access](https://sovaria.in/docs/row-level-security)).

## Options

| Option | Default | What it does |
|---|---|---|
| `persistSession` | On in browsers when an anon key is given | `true` keeps the session in `localStorage`; `false` keeps it in memory only; `{ storage, key }` uses another synchronous store. |
| `results` | `'rows'` | `'supabase'`: awaited `from(table)` queries resolve to `{ data, error, count, status }` and never throw, like supabase-js (`.throwOnError()` opts one query back). Default: the rows, and errors throw a `SovariaError` ([Migrate from Supabase or Firebase](https://sovaria.in/docs/migrate-from-supabase-or-firebase)). |
| `onTokenRefresh` | — | Called with new tokens after sign-in or refresh (without the refresh token). |
| `onTokenRefreshSensitive` | — | The same, including the refresh token — store it securely, never log it. |
| `accessToken`, `expiresIn` | — | Start with an existing token. |
| `envId` | Production | Talk to another environment of the project. |
| `orgId`, `projectId` | Discovered from the URL | Pin them for multi-project tools. |

Retry and transport settings are set when you construct the client directly: `new SovariaSDK({ baseUrl, accessToken, refreshToken, persistSession, fetchImpl, retryCount, retryBaseDelayMs, retryBudgetMs, onConnectionState })`.

## Retries and idempotency

- A call rides through a passing problem for up to 12 seconds (`retryBudgetMs`, also per call) before it fails: no connection or no answer, or the server busy or restarting (`429`, `502`, `503`, `504`). Waits grow from 100 ms (`retryBaseDelayMs`) to at most 3 s, with jitter; a `Retry-After` the server sends is honoured within those 12 seconds, with jitter on top, up to 5 s for a `429` and 10 s for a `503` (a longer one is returned to you as `retryAfterSeconds`). `retryCount` (default 10) caps the attempts; `retryBudgetMs: 0` leaves only that cap. The window bounds the waits between attempts: a first attempt that hangs still waits up to `timeoutMs`, later ones at most what is left of the window (at least 5 s). A `500` is usually a bug: it gets 3 quick attempts in the TypeScript and Python SDKs, none in Flutter, Swift and Kotlin. A plan or quota refusal is never retried.
- While one call is retrying a service that is down or overloaded, the client's other failing calls to that service wait behind it instead of each retrying, then go again once it gets through (after their own `Retry-After`, if they were told one): a restart doesn't turn into a flood of retries, and calls to other services aren't held up. In a browser with no connection, a call waits for the connection to come back (within the same 12 seconds) instead of failing at once. With offline-first on ([Offline-first apps](https://sovaria.in/docs/offline-first)), the offline layer's own reads and writes don't wait: they answer from the cache or the write queue at once when the device has no connection, and within about 1.5 s when the server can't be reached (a connection that hangs is given up after 5 s). Your other calls (sign-in, files, functions) keep the full window.
- Python, Flutter, Swift and Kotlin behave the same way: `retry_budget_s` / `retryBudget` / `retryBudgetMs` and `on_connection_state` / `onConnectionState` (Python detects "offline" from a failed DNS lookup; mobile from the platform's "not connected" errors). The token is settled once per call, so every attempt of a write carries the same one; a token refresh rides a restart for up to 4 seconds. Connection-state listeners are called in order on an SDK background thread or queue in Kotlin and Swift (hop to your UI thread from them), so a listener that blocks never holds up a call. HTTP functions called with `functions.fetch` and event streams are not retried: their response is yours.
- Writes (`POST`, `PUT`, `PATCH`, `DELETE`) carry one `Idempotency-Key` from their first attempt and are sent again only where that can't apply them twice: after no answer or a `502`/`504` (the server deduplicates by the key: a retry gets the stored answer), or when nothing was done: a `429` or `503` the gateway marks `X-Sovaria-Refused: before-forward` (its rate limits, overload shedding and circuit breaker; the `429` with `Retry-After`), or a function call Forge refused with `RUNNER_BUSY` and `X-Sovaria-Runner-Refused: before-start` (it never started). Only these headers count, never the body's code: a service, or your own HTTP function, can answer `503` with any code after doing its work, so a write is not sent again after a service's own `503` or `429`, or when the gateway says it couldn't deduplicate (`X-Sovaria-Idempotency: unavailable`). Reads are sent again after any `429`, `502`, `503` or `504`. A retry that arrives while the first try is still running waits for it; if the window ends first, the error has `outcomePending` (and `isTransient`): try again later with the same key, never a new one. If the first try's outcome is unknown (the server timed out after receiving it), the retry fails with `409 IDEMPOTENCY_OUTCOME_UNKNOWN` instead of applying the write twice: check whether it happened before sending it again.
- The key belongs to one call. To make a write safe for your own code to repeat (after a crash or a page reload, say), pass a key you can recreate, such as `order-<id>`: `sovaria.request(method, path, { body, idempotencyKey })`. The server keeps the answer for an hour (two minutes when it carries tokens or keys); the same key with a different body gets `409 IDEMPOTENCY_PAYLOAD_MISMATCH`. `idempotent: true` is no longer needed and is still accepted.
- Access tokens are refreshed a minute before they expire, and once more after a `401`; you don't need to handle expiry yourself.

## Connection state

Show a quiet "Reconnecting…" instead of an error while calls are being retried. `onConnectionState` (or `sovaria.onConnectionStateChange(listener)`, which returns an unsubscribe function) is called on each change: `reconnecting` while a call waits to retry, `offline` while the device has no connection, `unavailable` when a call gave up, and `online` once an answer arrives again. `sovaria.connectionState()` gives the current one.

TypeScript:
```ts
const off = sovaria.onConnectionStateChange((state) => {
  banner.hidden = state === 'online'
  banner.textContent = state === 'offline' ? "You're offline" : 'Reconnecting…'
})
```

The state comes from what calls are doing now: one call that is cancelled or gives up doesn't leave a stale "reconnecting" behind, and another call succeeding meanwhile doesn't make it flicker. A live realtime connection counts as "online" too. When a call does fail, `err.isOffline` says the device had no connection (the `code` stays `NETWORK_ERROR`, or `UNAVAILABLE` in Flutter, Swift and Kotlin, so existing checks keep working), and `err.isTransient` says it may work later (no answer, `429`, `502`, `503`, `504`, or a write still running). A refusal such as `403` is neither.

## Errors

Failed calls throw `SovariaError` with a stable `code` to branch on and a `message` you can show to users:

TypeScript:
```ts
import { SovariaError } from '@sovaria/sdk'

try {
  await sovaria.data.sql('insert into orders (total) values ($1)', [42])
} catch (err) {
  if (!(err instanceof SovariaError)) throw err
  switch (err.code) {
    case 'UNAUTHENTICATED': return goToSignIn()
    case 'PERMISSION_DENIED': return toast('You can\'t do that.')
    case 'PLAN_LIMIT_REACHED':
    case 'PLAN_QUOTA_EXHAUSTED': return showUpgrade(err.detail)
    case 'RATE_LIMITED': return toast('Too many requests — try again in a moment.')
    default: console.error(err.technicalMessage); toast(err.message)
  }
}
```

| Field | Value |
|---|---|
| `code` | `NETWORK_ERROR`, `UNAUTHENTICATED`, `PERMISSION_DENIED`, `NOT_FOUND`, `CONFLICT`, `INVALID_INPUT`, `PAYLOAD_TOO_LARGE`, `UNSUPPORTED_TYPE`, `RATE_LIMITED`, `PLAN_LIMIT_REACHED`, `PLAN_FEATURE_REQUIRED`, `PLAN_QUOTA_EXHAUSTED`, `SERVICE_UNAVAILABLE`, `SERVER_ERROR`, `BAD_REQUEST`, `CONFIG_ERROR`, `UNKNOWN` |
| `message` | A friendly sentence for end users. |
| `statusCode` | The HTTP status (`0` when no response arrived). |
| `serverCode` | The server's own code when it sent one (`SIGNUP_DISABLED`, …). |
| `detail` | The response body. |
| `technicalMessage` | `HTTP <status>: <server text>` for logs. |

## Troubleshooting

| Symptom | Fix |
|---|---|
| `403 ORIGIN_NOT_ALLOWED` in the browser | Add your site's origin under Project Settings › API ([Allowed origins (CORS) for browser apps](https://sovaria.in/docs/allowed-origins)). |
| `CONFIG_ERROR` at start-up (`Missing portal URL`, `Missing SOVARIA_URL`) | The URL isn't set — check the variable names and that your bundler exposes them (`VITE_`, `NEXT_PUBLIC_`). |
| Warning: `publishableKey looks like a user JWT` | A session token was passed where the anon key belongs; pass tokens with `setAccessToken`. |
| Signed out after every reload | Sessions persist by default only in browsers with an anon key; on servers pass the user's token per request. |
| Every call is `PERMISSION_DENIED` | Your rules don't allow it yet — see [How access is decided](https://sovaria.in/docs/access-model). |
