JavaScript SDK
Install @sovaria/sdk, create a client, keep users signed in, handle errors and retries — and find every method by area.
@sovaria/sdk 0.15.0 is the official JavaScript and TypeScript client for Sovaria. It runs anywhere fetch is available — modern browsers, Node.js 18+ and edge runtimes — and takes a fetchImpl option for anything else. It signs users in and keeps their session, scopes every call to your project, retries safely, and returns typed results.
#Install
npm install @sovaria/sdk#Create a client
Use the project URL and anon key from the console's Connect panel. One client per app is enough; it is safe to import it everywhere.
createClientFromProjectConfig
Create a client from sovaria.config.json.
createClientFromProjectConfig(
raw: SovariaProjectConfigFile,
options?: ProjectConfigOptions = {},
): SovariaSDK<"rows", UntypedDatabase>In a bundler, import the file and pass the anon key: createClientFromProjectConfig(config, { publishableKey: import.meta.env.VITE_SOVARIA_ANON_KEY }).
Parameters
rawSovariaProjectConfigFilerequired- The parsed
sovaria.config.json(fromsov link). optionsProjectConfigOptionsoptionaldefault{}- Override values such as the anon key.
Returns
SovariaSDK<"rows", UntypedDatabase>
import config from './sovaria.config.json'
import { createClientFromProjectConfig } from '@sovaria/sdk'
const sovaria = createClientFromProjectConfig(config, { anonKey: import.meta.env.VITE_SOVARIA_ANON_KEY })createClient
Create a client.
createClient(
url: string,
key: string | undefined,
options: Omit<SovariaPortalConfig, 'url' | 'baseUrl'> & { results: 'supabase' },
): SovariaSDK<"supabase", DB>Either pass the two values from the console's Connect panel — createClient('https://<ref>.sovarias.in', '<anon-key>') — or a config object.
Parameters
urlstringrequiredkeystring | undefinedrequired- The anon key (browsers, apps) or a server key (backends only).
optionsOmit<SovariaPortalConfig, 'url' | 'baseUrl'> & { results: 'supabase' }required- Extra settings such as
persistSessionandonTokenRefresh.
Returns
SovariaSDK<"supabase", DB>
import { createClient } from '@sovaria/sdk'
const sovaria = createClient('https://<project-ref>.sovarias.in', '<anon-key>')createClient
Create client.
createClient(
config: SovariaPortalConfig & { results: 'supabase' },
): SovariaSDK<"supabase", DB>Parameters
configSovariaPortalConfig & { results: 'supabase' }required
Returns
SovariaSDK<"supabase", DB>
import { createClient } from '@sovaria/sdk'
const sovaria = createClient('https://<project-ref>.sovarias.in', '<anon-key>')createClient
With no arguments: from the environment (SOVARIA_URL plus SOVARIA_ACCESS_TOKEN, SOVARIA_PUBLISHABLE_KEY or SOVARIA_ANON_KEY; with none of those, SOVARIA_SERVICE_ROLE_KEY or the function's own SOVARIA_FUNCTION_KEY).
createClient(): SovariaSDK<"rows", DB>Inside a Sovaria function this is all it takes.
Returns
SovariaSDK<"rows", DB>
import { createClient } from '@sovaria/sdk'
const sovaria = createClient('https://<project-ref>.sovarias.in', '<anon-key>')createClient
Create client.
createClient(
urlOrConfig: string | SovariaPortalConfig,
key?: string,
options?: Omit<SovariaPortalConfig, 'url' | 'baseUrl'>,
): SovariaSDK<"rows", DB>Parameters
urlOrConfigstring | SovariaPortalConfigrequired- The project URL from Connect (or a full config object).
keystringoptional- The anon key (browsers, apps) or a server key (backends only).
optionsOmit<SovariaPortalConfig, 'url' | 'baseUrl'>optional- Extra settings such as
persistSessionandonTokenRefresh.
Returns
SovariaSDK<"rows", DB>
import { createClient } from '@sovaria/sdk'
const sovaria = createClient('https://<project-ref>.sovarias.in', '<anon-key>')createClient
Create client.
createClient(
urlOrConfig?: string | SovariaPortalConfig,
key?: string,
options?: Omit<SovariaPortalConfig, 'url' | 'baseUrl'> = {},
): SovariaSDK<ResultMode, UntypedDatabase>Parameters
urlOrConfigstring | SovariaPortalConfigoptional- The project URL from Connect (or a full config object).
keystringoptional- The anon key (browsers, apps) or a server key (backends only).
optionsOmit<SovariaPortalConfig, 'url' | 'baseUrl'>optionaldefault{}- Extra settings such as
persistSessionandonTokenRefresh.
Returns
SovariaSDK<ResultMode, UntypedDatabase>
import { createClient } from '@sovaria/sdk'
const sovaria = createClient('https://<project-ref>.sovarias.in', '<anon-key>')#Sessions, tokens and scope
In browsers the client keeps the app user's session in localStorage and refreshes it before it expires (persistSession, on by default with an anon key). On servers, pass tokens in or let the client discover its scope from the project URL.
sovaria.setApiVersion
Pin later function calls to a functions API version ('v1'), or pass null for the live code.
sovaria.setApiVersion(version: string | null): voidParameters
versionstring | nullrequired
Returns
void
sovaria.fromPortalConfig
From portal config.
sovaria.fromPortalConfig(
config: SovariaPortalConfig,
): SovariaSDK<ResultMode, UntypedDatabase>Parameters
configSovariaPortalConfigrequired
Returns
SovariaSDK<ResultMode, UntypedDatabase>
sovaria.fromEnv
From env.
sovaria.fromEnv(
env?: Record<string, string | undefined> = {},
): SovariaSDK<"rows", UntypedDatabase>Parameters
envRecord<string, string | undefined>optionaldefault{}- Defaults to
process.env.
Returns
SovariaSDK<"rows", UntypedDatabase>
- Reads the URL, key and scope from environment variables — handy in servers and CI.
sovaria.setAccessToken
Set access token.
sovaria.setAccessToken(
token: string,
options?: { expiresIn?: number } = {},
): thisParameters
tokenstringrequired- An access token you stored earlier.
options{ expiresIn?: number }optionaldefault{}expiresInseconds, so the SDK refreshes in time.
Returns
this
sovaria.setRefreshToken
Set refresh token.
sovaria.setRefreshToken(token: string): thisParameters
tokenstringrequired- A refresh token you stored earlier.
Returns
this
sovaria.clearAccessToken
Clear access token.
sovaria.clearAccessToken(): thisReturns
this
sovaria.setScope
Set scope.
sovaria.setScope(scope: SovariaScope): thisParameters
scopeSovariaScoperequired{ orgId, projectId, envId? }— which project (and environment) calls go to.
Returns
this
sovaria.setScope({ orgId, projectId, envId: stagingEnvId })sovaria.clearScope
Clear scope.
sovaria.clearScope(): thisReturns
this
sovaria.resolveScope
The org/project this client talks to.
sovaria.resolveScope(): Promise<SovariaScope | undefined>Set explicitly with setScope(), or discovered once from the project URL (https://<ref>.sovarias.in) — so createClient(projectUrl, anonKey) is enough.
Returns
Promise<SovariaScope | undefined> — The org/project/environment this client uses, discovered from the project URL once and cached.
sovaria.getScopeHeaders
Get scope headers.
sovaria.getScopeHeaders(): Record<string, string>Returns
Record<string, string>
sovaria.getRealtimeWebSocketUrl
Get realtime web socket url.
sovaria.getRealtimeWebSocketUrl(
channel: string,
ticket?: string,
): stringParameters
channelstringrequiredticketstringoptional
Returns
string
sovaria.issueRealtimeWebSocketTicket
Issue realtime web socket ticket.
sovaria.issueRealtimeWebSocketTicket(channel: string): Promise<string>Parameters
channelstringrequired
Returns
Promise<string>
sovaria.getRealtimeWebSocketUrlWithTicket
Get realtime web socket url with ticket.
sovaria.getRealtimeWebSocketUrlWithTicket(
channel: string,
): Promise<string>Parameters
channelstringrequired
Returns
Promise<string>
sovaria.enableOffline
Offline-first documents: reads fall back to a local cache, offline writes are applied locally at once and queued, and everything syncs in order when the connection is back.
sovaria.enableOffline(options?: OfflineOptions = {}): OfflineControllerCall once, before reading or writing documents.
``ts const offline = sov.enableOffline({ storage: indexedDbStorage(), onSyncError: (e, writes) => console.warn(e, writes) })
Parameters
optionsOfflineOptionsoptionaldefault{}
Returns
OfflineController
sovaria.collection
A document collection (or users/alice/posts subcollection): field queries, cursors, live listeners and add.
sovaria.collection(path: string): Query<T>ts const snap = await sov.collection('posts').where('tags', 'array-contains', 'news').orderBy('at', 'desc').limit(20).get()
Parameters
pathstringrequired
Returns
Query<T>
sovaria.collectionGroup
Every collection with this id at any depth (comments, posts/p1/comments, …), like Firestore's collectionGroup.
sovaria.collectionGroup(collectionId: string): Query<T>Access rules and row policies apply per matched collection; onSnapshot is a live listener on the whole group.
``ts const top = await sov.collectionGroup('comments').where('flagged', '==', true).orderBy('at', 'desc').get()
Parameters
collectionIdstringrequired
Returns
Query<T>
sovaria.doc
A document reference: get, set (merge), create, update with FieldValue transforms, delete, onSnapshot.
sovaria.doc(path: string): DocumentReference<T>Parameters
pathstringrequired
Returns
DocumentReference<T>
sovaria.from
Rows of a table or view through the REST API (/rest/v1/<table>): select/filters/order/range/single, insert, upsert, update, delete, count, subscribe.
sovaria.from(
table: string,
): TableRef<TableRow, M, Partial<TableRow>, Partial<TableRow>>Typed from the Database type given to createClient<Database>().
Parameters
tablestringrequired- A table or view of the project's database.
Returns
TableRef<TableRow, M, Partial<TableRow>, Partial<TableRow>> — A table reference: start a read (select), count, a write (insert, upsert, update, delete) or subscribe. Await the query to run it.
- The way apps read and write rows (the REST API,
/rest/v1/<table>): values are bound, never spliced into SQL, and each table's access rules decide what the user may do. - Filters:
eq neq gt gte lt lte like ilike is in contains containedBy overlaps textSearch match not or filter; reads also takeorder,limit,offset,range,single()andmaybeSingle(). insert(object)resolves to the stored row (its id, defaults and an owner column filled in by the database);updateanddeleteneed a filter.select('*', { count: 'exact' })resolves to{ rows, count }; related rows embed by foreign key:select('id,title,author:authors(name)').
const books = await sovaria.from('books').select('id,title,author:authors(name)').eq('genre', 'sci-fi').order('title').limit(20)
const club = await sovaria.from('clubs').insert({ name: 'Readers' }) // { id, name, owner_id, created_at }
await sovaria.from('club_members').insert({ club_id: club.id }) // user_id = the signed-in user
await sovaria.from('books').update({ title: 'Dune' }).eq('id', id)
const reviews = await sovaria.from('reviews').count().eq('book_id', id)
const stop = sovaria.from('reviews').subscribe(() => reload())sovaria.rpc
Call a Postgres function: await sovaria.rpc('top_books', { days: 7 }).
sovaria.rpc(
fn: string,
args?: unknown = {},
options?: TableRpcOptions = {},
): RpcQuery<unknown, M>One that returns rows takes filters, order, range and single() like a table read; { get, head, count } options. POST /rest/v1/rpc/{fn}
Parameters
fnstringrequired- A Postgres function of the project.
argsunknownoptionaldefault{}- Its arguments by name.
optionsTableRpcOptionsoptionaldefault{}get(a read-only function, arguments in the query string),headwithcount(only count the rows).
Returns
RpcQuery<unknown, M> — A query: await it for the result, or chain eq/order/limit/range/single first (a function that returns rows). { data, error, count } in supabase mode.
- App users need a policy that allows
fn:<name>. - With
createClient<Database>()the arguments and result are typed fromsov gen types typescript.
const top = await sovaria.rpc('top_books', { days: 7 }).eq('genre', 'sci-fi').order('score', { ascending: false }).limit(5)sovaria.graphql
GraphQL on /graphql/v1 (pg_graphql style: { notesCollection { edges { node { id title } } } }), as the signed-in user (row-level security applies) or with the anon key.
sovaria.graphql(
query: string,
variables?: Record<string, unknown>,
options?: { operationName?: string } = {},
): Promise<{ data: T | null; errors?: JsonObject[] | undefined; }>Resolves to { data, errors }: mistakes in the query come back in errors; a refused request (no key, plan, rate limit) throws a SovariaError.
Parameters
querystringrequiredvariablesRecord<string, unknown>optionaloptions{ operationName?: string }optionaldefault{}
Returns
Promise<{ data: T | null; errors?: JsonObject[] | undefined; }>
- HTTP
- POST /graphql/v1
sovaria.channel
A realtime channel, supabase-js style: .on('broadcast' | 'presence' | 'postgres_changes', filter, cb), then .subscribe(); send(), track(), presenceState(), unsubscribe().
sovaria.channel(
name: string,
options?: RealtimeChannelOptions = {},
): SovariaRealtimeChannelSovaria's own realtime.channel(name, handlers) (replay after reconnects, gaps, E2EE) is still there.
Parameters
namestringrequired- Channel name (
realtime:is accepted and dropped). optionsRealtimeChannelOptionsoptionaldefault{}config.broadcast.self(get your own broadcasts),config.broadcast.ack(wait for the server),config.presence.key.
Returns
SovariaRealtimeChannel — A channel: on('broadcast', { event }, cb), on('presence', { event: 'sync' | 'join' | 'leave' }, cb), on('postgres_changes', { event, schema, table }, cb), then subscribe(status => …); send, track, untrack, presenceState, unsubscribe.
const room = sovaria.channel('room-1')
room
.on('broadcast', { event: 'cursor' }, ({ payload }) => moveCursor(payload))
.on('presence', { event: 'sync' }, () => setOnline(room.presenceState()))
.on('postgres_changes', { event: 'INSERT', schema: 'public', table: 'messages' }, () => reloadMessages())
.subscribe(async (status) => { if (status === 'SUBSCRIBED') await room.track({ online_at: Date.now() }) })
await room.send({ type: 'broadcast', event: 'cursor', payload: { x: 10, y: 20 } })sovaria.getChannels
The channels made with channel() that are still open.
sovaria.getChannels(): SovariaRealtimeChannel[]Returns
SovariaRealtimeChannel[]
sovaria.removeChannel
Unsubscribe a channel and forget it.
sovaria.removeChannel(
channel: SovariaRealtimeChannel,
): Promise<"ok" | "error">Parameters
channelSovariaRealtimeChannelrequired
Returns
Promise<"ok" | "error"> — 'ok' once the channel's sockets are closed.
sovaria.removeAllChannels
Unsubscribe every channel made with channel().
sovaria.removeAllChannels(): Promise<("ok" | "error")[]>Returns
Promise<("ok" | "error")[]>
sovaria.batch
Writes committed together: every one or none.
sovaria.batch(): WriteBatchReturns
WriteBatch
sovaria.runTransaction
Read then write atomically; retried (up to maxAttempts) when a document it read changes meanwhile.
sovaria.runTransaction(
fn: (tx: Transaction) => Promise<R>,
maxAttempts?: number = 5,
): Promise<R>Parameters
fn(tx: Transaction) => Promise<R>requiredmaxAttemptsnumberoptionaldefault5
Returns
Promise<R>
sovaria.request
Request.
sovaria.request(
method: string,
path: string,
options?: RequestOptions = {},
): Promise<T>Parameters
methodstringrequired- HTTP method.
pathstringrequired- API path, e.g.
/api/v1/sql/query. optionsRequestOptionsoptionaldefault{}query,body,headers,idempotencyKey/idempotent,responseType.
Returns
Promise<T>
- For endpoints the typed methods don't cover yet. Retries, auth and scope headers work the same.
sovaria.rateLimit
The gateway's request allowance as the last response stated it (X-RateLimit-*), or null before one did.
sovaria.rateLimit(): RateLimitInfo | nullFor backing off before a 429: if ((sovaria.rateLimit()?.remaining ?? 1) === 0) wait(...).
Returns
RateLimitInfo | null
#Errors
Every failed call throws a SovariaError with statusCode, code (a stable category to branch on), serverCode (the server's own code, e.g. PLAN_LIMIT_REACHED), detail (the response body) and technicalMessage (for logs). Its message is safe to show to users.
import { SovariaError } from '@sovaria/sdk'
try {
await sovaria.data.sql('select * from orders')
} catch (err) {
if (err instanceof SovariaError) {
if (err.code === 'UNAUTHENTICATED') return redirectToSignIn()
if (err.code === 'PLAN_LIMIT_REACHED') return showUpgrade(err.detail)
console.error(err.technicalMessage)
}
throw err
}code | Meaning (the default message) |
|---|---|
NETWORK_ERROR | Can't reach the server. Check your connection and try again. |
UNAUTHENTICATED | |
PERMISSION_DENIED | You don't have permission to do that. |
NOT_FOUND | We couldn't find what you were looking for. |
CONFLICT | |
INVALID_INPUT | |
PAYLOAD_TOO_LARGE | |
UNSUPPORTED_TYPE | That file type isn't allowed here. |
RATE_LIMITED | |
PLAN_LIMIT_REACHED | This project has reached its plan limit. |
PLAN_FEATURE_REQUIRED | This feature isn't available on the current plan. |
PLAN_QUOTA_EXHAUSTED | This project's usage quota is used up for now. |
SERVICE_UNAVAILABLE | |
SERVER_ERROR | |
BAD_REQUEST | That request couldn't be completed. |
CONFIG_ERROR | |
OFFLINE_QUEUE_FULL | You're offline and too many changes are waiting to sync. Reconnect, then try again. |
UNKNOWN |
#Retries and idempotency
Failed calls with status 429, 500, 502, 503 or 504 are retried with exponential backoff; 429 and 409 IDEMPOTENCY_IN_PROGRESS wait for the server's Retry-After. Every write (POST, PUT, PATCH, DELETE) carries one Idempotency-Key on all its attempts, from the first, so a retried write runs only once on the server; pass idempotencyKey to sovaria.request() to choose the key yourself. Tune it with retryCount and retryBaseDelayMs on new SovariaSDK({ … }).