Create one client per project and reuse it across your app.
JavaScript
import { createClient } from 'stitchdb-js'
export const stitchdb = createClient('https://<project-ref>.p.stitchdb.com', '<anon-key>', {
auth: { persistSession: true, autoRefreshToken: true },
})Use the anon key in browsers and mobile apps. Use the service_role key only on servers you control: it bypasses Row Level Security.
#Options
| Option | Default | Purpose |
|---|---|---|
db.schema | 'public' | The schema queries use (switch per query with stitchdb.schema('name')). |
auth.persistSession | true | Store the session (localStorage in browsers). |
auth.autoRefreshToken | true | Refresh the access token before it expires. |
auth.detectSessionInUrl | true | Pick up the session from e-mail and OAuth redirects. |
auth.flowType | 'implicit' | Use 'pkce' for server-rendered apps. |
auth.storage, auth.storageKey | localStorage | Where the session is stored. |
global.headers | Headers sent with every request. | |
global.fetch | global fetch | A custom fetch implementation. |
realtime.params | Realtime options, for example { eventsPerSecond: 10 }. |
#On a server
JavaScript
const admin = createClient(process.env.STITCHDB_URL, process.env.STITCHDB_SERVICE_ROLE_KEY, {
auth: { persistSession: false, autoRefreshToken: false },
})#Custom headers
JavaScript
// Force one read to the primary (for example right after a write)
const { data } = await stitchdb.from('orders').select('*').eq('id', 42).setHeader('X-Stitch-Read', 'primary')
// Or for every request of a client
const writer = createClient('https://<project-ref>.p.stitchdb.com', '<anon-key>', { global: { headers: { 'X-Stitch-Read': 'primary' } } })