Docs

JavaScript: install and configure

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.

Updated Nov 25, 2026

#Install

npm install @sovaria/sdk
Runs inNotes
BrowsersModern 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.jsAny version with global fetch (18+). Pass fetchImpl to use another implementation.
Deno, Bun, edge runtimesUses the global fetch and Web Crypto.
React NativepersistSession: { 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).

#Create a client

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,
)

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; variable names: 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). 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.

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).

#Options

OptionDefaultWhat it does
persistSessionOn in browsers when an anon key is giventrue 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).
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.
envIdProductionTalk to another environment of the project.
orgId, projectIdDiscovered from the URLPin 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), 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.

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:

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)
  }
}
FieldValue
codeNETWORK_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
messageA friendly sentence for end users.
statusCodeThe HTTP status (0 when no response arrived).
serverCodeThe server's own code when it sent one (SIGNUP_DISABLED, …).
detailThe response body.
technicalMessageHTTP <status>: <server text> for logs.

#Troubleshooting

SymptomFix
403 ORIGIN_NOT_ALLOWED in the browserAdd your site's origin under Project Settings › API (Allowed origins (CORS) for browser apps).
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 JWTA session token was passed where the anon key belongs; pass tokens with setAccessToken.
Signed out after every reloadSessions persist by default only in browsers with an anon key; on servers pass the user's token per request.
Every call is PERMISSION_DENIEDYour rules don't allow it yet — see How access is decided.

#Coming from Firebase or Supabase?

PlatformWhat this is called there
FirebaseFirebase JavaScript SDK setup
Supabasesupabase-js createClient
SovariaJavaScript: install and configure

Moving an existing app? Migrate from Supabase or Firebase imports users (with their passwords), data, files and rules.