JavaScript / TypeScript SDK
Install and use the AltBase JS/TS SDK to query data, authenticate users, manage files, subscribe to realtime events, invoke functions, search, and more.
Installation
npm install @altbasedb/sdk
The package ships with full TypeScript declarations. No additional @types package is required.
Creating a Client
import { createClient } from '@altbasedb/sdk'
const altbase = createClient(
'http://localhost:4000',
'your-anon-key',
)
createClient accepts an optional third argument with advanced options:
interface AltBaseClientOptions {
url: string
apiKey: string
accessToken?: string // pre-set a JWT for authenticated requests
fetch?: typeof fetch // custom fetch implementation (useful in SSR)
retry?: RetryOptions // automatic retry configuration
storage?: SessionStorage // custom session storage adapter
}
The returned AltBaseClient exposes sub-clients and convenience methods:
| Property / Method | Purpose |
|---|---|
altbase.auth | Authentication (signup, login, OAuth, TOTP, SSO, sessions) |
altbase.storage | File storage (upload, download, signed URLs) |
altbase.realtime | WebSocket subscriptions (CDC, broadcast, presence) |
altbase.vector | Vector embeddings and RAG search |
altbase.search | Full-text search |
altbase.events | Event publishing and subscription |
altbase.graphql | GraphQL query and mutation execution |
altbase.mcp | MCP tool and resource invocation |
altbase.functions | Serverless function invocation |
altbase.workflows | Workflow invocation and monitoring |
altbase.from(table) | Start a query via the fluent QueryBuilder |
altbase.sql(query) | Execute raw SQL (requires service key) |
altbase.channel(name) | Shortcut for altbase.realtime.channel(name) |
SSR Support
The SDK ships a separate entry point for server-side rendering:
import { createClient } from '@altbasedb/sdk/ssr'
This export is optimized for server environments and avoids browser-specific APIs.
Querying Data with QueryBuilder
Every call to altbase.from(table) returns a QueryBuilder<T> instance. Chain methods to build your query, then await the result.
Select
const { data, error } = await altbase
.from('posts')
.select('id, title, created_at')
.order('created_at', { ascending: false })
.limit(20)
Filter Methods
| Method | Operator | Example |
|---|---|---|
.eq(col, val) | = | .eq('status', 'published') |
.neq(col, val) | != | .neq('role', 'admin') |
.gt(col, val) | > | .gt('age', 18) |
.gte(col, val) | >= | .gte('price', 10) |
.lt(col, val) | < | .lt('stock', 5) |
.lte(col, val) | <= | .lte('priority', 3) |
.like(col, pat) | LIKE | .like('name', '%smith%') |
.ilike(col, pat) | ILIKE | .ilike('email', '%@gmail.com') |
.in(col, vals) | IN | .in('id', [1, 2, 3]) |
.is(col, val) | IS | .is('deleted_at', 'null') |
Modifiers
| Method | Example | Notes |
|---|---|---|
.order(col, opts?) | .order('created_at', { ascending: false }) | Default ascending |
.limit(n) | .limit(10) | Cap result count |
.range(from, to) | .range(0, 9) | Offset pagination |
.single() | .eq('id', 1).single() | Returns T | null instead of array |
.maybeSingle() | .eq('id', 1).maybeSingle() | Same as single, no error on zero rows |
Insert, Update, Delete
await altbase.from('posts').insert({ title: 'Hello', body: 'First post' })
await altbase.from('posts').update({ title: 'Updated' }).eq('id', 42)
await altbase.from('posts').delete().eq('id', 42)
Insert and update set Prefer: return=representation automatically so affected rows are returned in data.
TypeScript Generics
Pass a type parameter to from for end-to-end type safety:
interface Post {
id: number
title: string
body: string
created_at: string
}
const { data } = await altbase.from<Post>('posts').select().eq('id', 1).single()
// data is typed as Post | null
Authentication
The altbase.auth module covers signup, login, session management, OAuth, TOTP, SSO, and account recovery.
Sign Up
const { data, error } = await altbase.auth.signUp({
email: 'user@example.com',
password: 'securepassword',
options: { data: { display_name: 'Jane' } },
})
Sign In
// Email + password
await altbase.auth.signInWithPassword({ email: 'user@example.com', password: 'secret' })
// Magic link (sends email)
await altbase.auth.signInWithMagicLink({ email: 'user@example.com' })
// OTP (sends SMS, then verify)
await altbase.auth.signInWithOtp({ phone: '+1234567890' })
await altbase.auth.verifyOtp({ phone: '+1234567890', token: '123456' })
// OAuth
await altbase.auth.signInWithOAuth({ provider: 'google' })
// SSO (enterprise)
await altbase.auth.signInWithSSO({ domain: 'acme.com' })
TOTP (Two-Factor Authentication)
// Enroll TOTP
const { data: enrollment } = await altbase.auth.mfa.enroll({ factorType: 'totp' })
// enrollment.totp.uri — use to generate QR code
// Verify TOTP
await altbase.auth.mfa.verify({ factorId: enrollment.id, code: '123456' })
Session, User, and Sign Out
altbase.auth.getSession() // { access_token, refresh_token } | null
await altbase.auth.getUser() // { data: User }
await altbase.auth.refreshSession() // rotates both tokens
await altbase.auth.updateUser({ data: { avatar_url: 'https://...' } })
await altbase.auth.resetPasswordForEmail('user@example.com')
await altbase.auth.signOut()
After sign-in the SDK stores tokens internally and attaches the access token to every request.
Supported OAuth Providers
type OAuthProvider =
| 'google' | 'github' | 'apple' | 'discord' | 'gitlab'
| 'bitbucket' | 'twitter' | 'facebook' | 'linkedin'
| 'microsoft' | 'slack' | 'spotify' | 'twitch'
Storage
Bucket Management
await altbase.storage.createBucket('avatars', { public: true })
const { data: buckets } = await altbase.storage.listBuckets()
await altbase.storage.deleteBucket('old-bucket')
File Operations
const bucket = altbase.storage.from('avatars')
await bucket.upload('user/avatar.png', file, { contentType: 'image/png' })
const { data: blob } = await bucket.download('user/avatar.png')
const { data: files } = await bucket.list('user/')
await bucket.remove(['user/avatar.png'])
// Signed URL (expires in 3600 seconds)
const { data } = await bucket.createSignedUrl('user/avatar.png', 3600)
// Public URL (bucket must be public)
const url = bucket.getPublicUrl('user/avatar.png')
Realtime
Subscribe to Postgres changes or custom broadcast events over WebSocket.
Database Changes
altbase
.channel('realtime:public:posts')
.on('INSERT', (event) => console.log('New:', event.new_record))
.on('UPDATE', (event) => console.log('Changed:', event.new_record))
.subscribe()
Topic format for database changes: realtime:{schema}:{table}.
Broadcast and Wildcard
const channel = altbase.channel('broadcast:chat-room')
channel.on('message', (payload) => console.log(payload))
channel.on('*', (event) => console.log(event)) // catch-all
channel.subscribe()
Cleanup
channel.unsubscribe() // leave one channel
altbase.realtime.disconnect() // close the WebSocket entirely
Vector Search & RAG
The altbase.vector module provides embedding generation and vector search.
// Vector similarity search
const results = await altbase.vector('proj_123').search(
'documents',
'embedding',
[0.1, 0.2, 0.3, /* ... */]
)
// Ask with citations (RAG)
const answer = await altbase.vector('proj_123').ask(
'support',
'How do we rotate API keys?'
)
Full-Text Search
const results = await altbase.search.query('contacts', {
query: 'jane smith',
fields: ['first_name', 'last_name', 'email'],
limit: 20,
})
Events
Publish and subscribe to application events via NATS.
// Publish
await altbase.events.publish('order.created', { order_id: '123' })
// Subscribe
await altbase.events.subscribe('order.created', (event) => {
console.log(event.data)
})
GraphQL
Execute GraphQL queries and mutations.
const { data } = await altbase.graphql.query(`
query {
posts(limit: 10) {
id
title
}
}
`)
Functions
Invoke serverless functions by slug.
const result = await altbase.functions.invoke('refresh-search', {
body: { table: 'posts' },
})
MCP
Invoke MCP tools and read MCP resources.
// List available tools
const tools = await altbase.mcp.listTools()
// Invoke a tool
const result = await altbase.mcp.invokeTool('atlas_query', {
table: 'users',
select: '*',
})
Raw SQL
For advanced queries that cannot be expressed through the QueryBuilder, use the sql method. This requires a service role API key.
const altbase = createClient(url, serviceKey)
const rows = await altbase.sql<{ count: number }>(
'SELECT count(*) FROM posts WHERE published = true'
)
Response Shape
All SDK methods return a consistent shape:
interface QueryResult<T> {
data: T[] | null
error: AltBaseError | null
count?: number
status: number
}
interface AltBaseError {
message: string
code?: string
status?: number
}
Always check error before consuming data.
Model Context Protocol (MCP)
MCP server for AI assistants with auto-generated database tools, JSON-RPC 2.0 transport, SSE streaming, per-project configuration, and RLS enforcement.
React SDK
Official React hooks for AltBase — data fetching with TanStack Query, realtime CDC subscriptions with automatic cache merging, auth state, and storage.