Skip to the page

Reference · SDKs

TypeScript

Call your deployed queries through a generated TypeScript client, and use napalm-client for sessions, live queries, actions, webhooks, uploads and search.

In the schema
—

Installation and generation#

Run napalm generate from your project folder after you write your query files. The SDKs overview covers the generated files and how deployed queries are called.

Sessions, streams and uploads

The client library manages sessions, bookmarks, live streams, local sync and uploads.

Generated query bindings

Code generation turns each query file into typed calls and live subscriptions.

--lang ts invokes openapi-typescript via npx and pairs with openapi-fetch.

Install once
npm install openapi-fetch napalm-client
app.ts
import createClient from 'openapi-fetch'import { NapalmClient } from 'napalm-client'import type { paths } from './napalm/schema'import { queries } from './napalm/queries' const napalm = new NapalmClient('https://<label>.napalmdata.com', { token: () => session })const db = createClient<paths>({  baseUrl: 'https://<label>.napalmdata.com',  // Attaches the current bearer token and tracks Napalm-Bookmark for read-your-own-writes consistency.  fetch: napalm.fetch,}) const { data, error } = await db.POST('/query/getNote', {  body: { query: queries.getNote, variables: { id } },})// data.data[0].author.name is typed as string.

Sign-in#

SignIn (in napalm-client and napalm_client) wraps your project’s sign-in routes. Every method runs the PKCE flow for you by generating a verifier, sending its SHA-256 challenge, exchanging the authorization code at GET /sign-in/token and saving the resulting session in your chosen store. Pass the SignIn instance to NapalmClient so every request carries the active session, including typed calls made through napalm.fetch (or napalm.httpClient in Dart). When the user signs in, signs out or switches accounts, the client clears active live-query rows immediately and resubscribes as the new caller. (If you supply a custom token callback instead of SignIn, call napalm.restart() whenever the bearer token changes.)

sign-in.ts
import { NapalmClient, SignIn, webStore } from 'napalm-client' const signIn = new SignIn('https://<label>.napalmdata.com', { store: webStore() })// Attaches the active session token and restarts live subscriptions when the user changes.const napalm = new NapalmClient('https://<label>.napalmdata.com', { signIn }) // Sign in with email and password.await signIn.withPassword(email, password) // OAuth redirect flow: navigate to the provider, then exchange the code on the callback page.location.assign(await signIn.providerUrl('builtin::oauth_google', { redirectTo: `${location.origin}/signed-in` }))await signIn.finish() // on /signed-in: exchanges ?code= with the stored PKCE verifier // Sign in with a WebAuthn passkey.await signIn.withPasskey(email)
Email and password
signUp, withPassword, verify, resendVerification, sendPasswordReset, resetPassword.
OAuth and OpenID Connect
Call providerUrl to start the redirect, then finish on the callback URL or deep link.
Magic links
Call sendCode to email a one-time code and link, then withCode for a typed code or finish on the callback link.
Passkeys
addPasskey and withPasskey in the client. For server-held sessions, call begin on the server, passkeyCode or addPasskeyCode in the browser and finish on the server.
Session state
session(), token, signOut(), signOutEverywhere(), pageToken() and onChange (TypeScript) or changes (Dart).

metadata() returns the application name, branding and enabled providers so your sign-in UI can render the configured sign-in methods dynamically. Redirect and email flows (OAuth providers, magic links and verification emails) persist their PKCE verifier in the configured store. Call finish against that same store on return, or the exchange throws no_verifier. When the project requires email verification, signUp and addPasskey return null until the user confirms the email address.

Pass store to choose where the session persists: webStore() uses localStorage and syncs sign-in and sign-out across browser tabs, memoryStore() keeps the session in memory, and any custom { get, set } adapter works for Keychain or Keystore storage. A session’s token lasts an hour and renews automatically, while revoked or expired sessions read as signed out. In React, useSession(signIn) from napalm-client/react subscribes to session changes.

SignIn runs directly in browsers. On React Native, napalm-client/expo provides secureStore(SecureStore) for Keychain or Keystore persistence and expoCrypto(Crypto) as the crypto option for random bytes and SHA-256. See the React Native guide for a complete setup.

In browsers, TypeScript passkey flows call navigator.credentials directly. On React Native, pass a native WebAuthn adapter in the passkeys option, and in Dart pass a Passkeys adapter backed by your platform’s passkey plugin. Authentication failures throw NapalmError (NapalmException in Dart) with a stable error code: no_identity_found (invalid email or password), verification_required, user_already_registered, verification_failed (invalid or expired code) and passkey_declined.

Action handlers#

When you attach an HTTPS action handler to a deployed query, handleCalls (and lower-level readCall + callerClient) in napalm-client verifies the incoming ES256 assertion against /.well-known/jwks.json, checks the request body’s SHA-256 digest before parsing JSON and exposes await call.db(). That call exchanges the assertion and your action secret at POST /sign-in/agents/token (RFC 8693) for a 60-second NapalmClient acting as the exact caller.

app/actions/[action]/route.ts
import { handleCalls } from 'napalm-client' export const POST = handleCalls(  {    async refundOrder(call) {      // Verified against /.well-known/jwks.json. call.rows is non-empty and policy-filtered.      const [order] = call.rows as { id: string; stripe_charge_id: string }[]      await stripe.refunds.create(        { charge: order.stripe_charge_id },        { idempotencyKey: call.job?.id ?? `refund:${order.id}` },      )      // Exchange call.assertion and secret at /sign-in/agents/token for a 60-second caller client.      const callerDb = await call.db()      await callerDb.fetch('https://<label>.napalmdata.com/query/markOrderRefunded', {        method: 'POST',        headers: { 'Content-Type': 'application/json' },        body: JSON.stringify({ variables: { order: order.id } }),      })      return { status: 'refunded' }    },  },  {    address: 'https://<label>.napalmdata.com',    handlers: 'https://api.example.com/actions',    secret: process.env.NAPALM_ACTION_SECRET,  },)

When an action is invoked by an ext::napalm::Job, call.job provides { id, attempt } so external calls can deduplicate on call.job.id. See Actions & background jobs for the full recipe.

Return accepted() to continue a long-running job asynchronously, then report progress with jobRun (step, steps, timeout, finish and fail). See Long jobs.

Live query hooks#

Every read-only query file also generates a typed live subscription helper. NapalmClient multiplexes all active subscriptions in your app onto a single SSE connection to POST /subscribe and applies incremental row patches as transactions commit. See Live queries for wire protocol details.

Multiplexed live queries

Active subscriptions share one SSE stream, apply diffs and clear on sign-out.

Offline device sync

Sync stores render cached rows offline and fetch only changes on reconnect.

In React (--lang ts), hooks.ts exports a typed hook for each read query, while live.ts exports framework-agnostic descriptors for napalm.subscribe.

App.tsx
import { NapalmClient } from 'napalm-client'import { NapalmProvider } from 'napalm-client/react'import { useGetNote } from './napalm/hooks' const napalm = new NapalmClient('https://<label>.napalmdata.com', { token: () => session }) function Note({ id }: { id: string }) {  const { rows } = useGetNote({ id })  return <h1>{rows?.[0]?.title}</h1>} export const App = () => <NapalmProvider client={napalm}><Note id={noteId} /></NapalmProvider>

Rows on the device#

sync caches a deployed query’s rows in a local store on the device so views render immediately, even offline. The store records the rows’ bookmark, requests only the diff since that bookmark on reconnect and applies incoming patches by id (removing any cached row omitted from the current result IDs, or replacing the cache with a full result when the change log no longer covers that bookmark). When the signed-in user changes, the client clears every open sync store. Offline caches & reconnect sync builds an app on sync.

Notes.tsx
import { indexedDbSyncStore } from 'napalm-client'import { useSyncedQuery } from 'napalm-client/react'import { live } from './napalm/live' // Create one persistent sync store per query.const notesStore = indexedDbSyncStore('notes') export function Notes() {  // Renders cached rows immediately, then applies live diffs from the server.  const { rows = [], isStored, error } = useSyncedQuery(live.listNotes, {}, notesStore)  if (error) return <p>{error.message}</p>  return (    <>      {isStored && <p>Showing saved notes</p>}      <ul>{rows.map((note) => <li key={note.id}>{note.title}</li>)}</ul>    </>  )}

indexedDbSyncStore(name) persists rows in IndexedDB in the browser, sqliteSyncStore(db, name) from napalm-client/expo persists rows in expo-sqlite on React Native, and memorySyncStore() keeps rows in memory. Outside React, pass the same query, variables and store to napalm.sync with onRows and onError callbacks.

Queries that return scalars or objects without top-level id fields fail with ids_required and leave the local store unchanged. Concurrent sync calls for the same query and variables share one subscription and store.

Webhooks#

When you attach a webhook to a schema notify trigger, Napalm POSTs a signed payload whenever matching writes commit. Use readDelivery to verify the Napalm-Signature HMAC-SHA256 header over the raw request bytes in constant time and parse the typed delivery. The delivery carries a kind (ping, rows, gap or test), an id for idempotency, the event and a causal position.

app/hooks/napalm/route.ts
import { NapalmClient, readDelivery } from 'napalm-client' const napalm = new NapalmClient('https://<label>.napalmdata.com', { token: serviceKey }) export async function POST(request: Request) {  // Verify Napalm-Signature over the raw request bytes in constant time.  const delivery = await readDelivery(await request.arrayBuffer(), request.headers, signingSecret)  if (delivery.kind === 'ping') queue.add({ event: delivery.event, position: delivery.position })  return new Response(null, { status: 204 })} // In the background worker: advance the session bookmark so reads include the triggering commit.napalm.reach(job.position)const { data } = await db.POST('/query/listUnsentOrders', { body: { variables: {} } })

Acknowledge the webhook promptly with a 2xx status and run heavy work in a background queue. Unacknowledged deliveries retry with exponential backoff. Pass delivery.position to napalm.reach(...) so subsequent worker reads observe at least the commit that triggered the webhook, even on a read replica. (On Node 18 without global Web Crypto, pass { subtle: webcrypto.subtle } from node:crypto.)

The change log#

changes pages through a branch’s committed transactions via GET /changes, filtered by the caller’s read access policies. Each item either lists committed row mutations (type, op, id and fields) or reports a gap when requested history predates retention. Start from an RFC 3339 timestamp with since, then pass each page’s next bookmark back as after. Because delivery is at-least-once, persist the cursor only after processing each page.

sync.ts
// Triggered by a ping webhook: page through committed changes from cursor up to delivery.position.for await (const page of napalm.changes({ types: ['Order'], after: cursor, reach: delivery.position })) {  for (const item of page.items) {    if (isGap(item)) await resync(item.gap)    else await warehouse.apply(item.rows)  }  if (page.next) cursor = await saveCursor(page.next)}

Pass reach to read through a target bookmark and stop (waiting briefly if the log has not caught up yet). Pairing reach with a ping webhook lets a worker tail the change log up to each ping’s position without polling. Omit reach in scheduled batch jobs to drain all available pages and return. To receive committed rows directly over HTTPS instead, bind a service key to the webhook.

File uploads#

Setting file_size in a mutation returns a one-time file_upload descriptor, and upload runs the rest of the upload lifecycle. Small files upload in one presigned PUT directly to object storage, while large files stream four parts in parallel, fetch part URLs on demand and retry failed transfers automatically. Once all bytes arrive, POST /uploads/complete verifies the byte size and header format and merges the new bookmark into the client session so immediate reads see the Ready file.

Interrupted multipart uploads resume from the last completed part. Each part uploads with a SHA-256 digest recorded by object storage, so calling upload again with the same file_upload descriptor and file transfers only missing parts. Keep the file_upload descriptor until verification succeeds.

upload.ts
const { data } = await db.POST('/query/addScan', {  body: { variables: { name: file.name, size: file.size } },})// Streams bytes directly to object storage (using multipart for large files) and verifies the upload.const facts = await napalm.upload(data.data[0].file_upload, file, {  onProgress: (sent, total) => setProgress(sent / total),})// facts.format is 'Pdf' and facts.content_type is 'application/pdf'.

Bytes that fail a schema format constraint throw the constraint’s message with code not_accepted, and the file_upload descriptor remains reusable until expiry. Pass a Blob, ArrayBuffer, typed array or UploadSource (size and read(start, end) for streaming chunks without holding the full file in memory). On React Native, fileSource from napalm-client/expo wraps a file on disk, and the subtle option supplies SHA-256 hashing.

Search and questions#

search calls POST /search to rank objects of one type by combined semantic and keyword relevance under the caller’s access rules. ask calls POST /ask, where a model synthesizes one EdgeQL statement for the question, runs it read-only as the caller and returns the rows alongside the statement. Both methods share the client’s session and causal bookmark.

search.ts
// Hybrid vector and full-text search filtered by the caller's access policies.const notes = await napalm.search<{ title: string }>('Note', 'plans for the launch', { limit: 5, fields: ['title'] }) // Natural-language query: reads run as the caller, while mutations return an unexecuted proposal.const { answer, data, proposed } = await napalm.ask('Which of my notes mention the launch?')

Streamed action answers#

streamAction calls an action and reads the handler’s answer as a stream. The call yields each frame as it arrives with its event name, raw text and parsed JSON. If the handler returns plain JSON instead of SSE, streamAction yields one answer frame. An error frame throws NapalmError (NapalmException in Dart), and an interrupted connection throws stream_ended. The stream’s bookmark merges into the client session so subsequent reads observe the handler’s writes.

summary.ts
// Read streamed SSE frames from the action handler. Breaking out of the loop aborts the request.for await (const frame of napalm.streamAction('summarizeNote', { note: noteId })) {  if (typeof frame.json === 'string') summary += frame.json} // In React: track streamed text and abort in-flight calls.const { text, isStreaming, error, call, stop } = useStreamedAction('summarizeNote')

In React, useStreamedAction(name) from napalm-client/react accumulates streamed text and returns call to invoke the action, stop to abort an active stream, isStreaming and error.

Type a word or two to search every docs page.