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.
#Install
npm install @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). |
#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
| 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). |
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; aRetry-Afterthe server sends is honoured within those 12 seconds, with jitter on top, up to 5 s for a429and 10 s for a503(a longer one is returned to you asretryAfterSeconds).retryCount(default 10) caps the attempts;retryBudgetMs: 0leaves only that cap. The window bounds the waits between attempts: a first attempt that hangs still waits up totimeoutMs, later ones at most what is left of the window (at least 5 s). A500is 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/retryBudgetMsandon_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 withfunctions.fetchand event streams are not retried: their response is yours. - Writes (
POST,PUT,PATCH,DELETE) carry oneIdempotency-Keyfrom their first attempt and are sent again only where that can't apply them twice: after no answer or a502/504(the server deduplicates by the key: a retry gets the stored answer), or when nothing was done: a429or503the gateway marksX-Sovaria-Refused: before-forward(its rate limits, overload shedding and circuit breaker; the429withRetry-After), or a function call Forge refused withRUNNER_BUSYandX-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 answer503with any code after doing its work, so a write is not sent again after a service's own503or429, or when the gateway says it couldn't deduplicate (X-Sovaria-Idempotency: unavailable). Reads are sent again after any429,502,503or504. A retry that arrives while the first try is still running waits for it; if the window ends first, the error hasoutcomePending(andisTransient): 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 with409 IDEMPOTENCY_OUTCOME_UNKNOWNinstead 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 gets409 IDEMPOTENCY_PAYLOAD_MISMATCH.idempotent: trueis 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)
}
}| 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). |
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. |
#Coming from Firebase or Supabase?
| Platform | What this is called there |
|---|---|
| Firebase | Firebase JavaScript SDK setup |
| Supabase | supabase-js createClient |
| Sovaria | JavaScript: install and configure |
Moving an existing app? Migrate from Supabase or Firebase imports users (with their passwords), data, files and rules.