On this page

Create a client

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

OptionDefaultPurpose
db.schema'public'The schema queries use (switch per query with stitchdb.schema('name')).
auth.persistSessiontrueStore the session (localStorage in browsers).
auth.autoRefreshTokentrueRefresh the access token before it expires.
auth.detectSessionInUrltruePick up the session from e-mail and OAuth redirects.
auth.flowType'implicit'Use 'pkce' for server-rendered apps.
auth.storage, auth.storageKeylocalStorageWhere the session is stored.
global.headersHeaders sent with every request.
global.fetchglobal fetchA custom fetch implementation.
realtime.paramsRealtime 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' } } })