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.

Session, live & upload runtime

Manages PKCE sign-in, causal Napalm-Bookmark headers, multiplexed SSE streams, local sync stores and resumable file uploads.

Generated deployed-query calls

napalm generate turns every .edgeql file in dbschema/queries into typed functions, live descriptors and reactive hooks or streams.

--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',  // Sends the caller's token as it stands now, 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 the 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 sign-in to NapalmClient, and every request carries the session, including typed calls made through napalm.fetch (or napalm.httpClient in Dart). When someone signs in, signs out or switches accounts, the client drops every live query’s rows immediately and re-subscribes as the new caller, so one person’s rows never linger on screen for the next person. (With a custom token function instead, call napalm.restart() whenever the bearer changes.)

sign-in.ts
import { NapalmClient, SignIn, webStore } from 'napalm-client' const signIn = new SignIn('https://<label>.napalmdata.com', { store: webStore() })// The client sends its session, and restarts its live queries when the person changes.const napalm = new NapalmClient('https://<label>.napalmdata.com', { signIn }) // Email and password.await signIn.withPassword(email, password) // A provider: leave for it, then finish on the page it returns to.location.assign(await signIn.providerUrl('builtin::oauth_google', { redirectTo: `${location.origin}/signed-in` }))await signIn.finish() // on /signed-in: trades the code in the address for the session // A passkey this device holds.await signIn.withPasskey(email)
Email and password
signUp, withPassword, verify, resendVerification, sendPasswordReset, resetPassword
OAuth and OpenID Connect
providerUrl to start, then finish on the provider’s return page (or deep link)
Magic links
sendCode, then withCode for a typed code or finish for a link
Passkeys
addPasskey, withPasskey. For a session a server keeps: begin on the server, passkeyCode or addPasskeyCode in the page and finish on the server
The session
session(), token, signOut(), signOutEverywhere(), pageToken() and onChange (TypeScript) or changes (Dart)

metadata() returns the app name, the brand and the enabled providers, so a sign-in page can render only the project’s sign-in options. A step that leaves the page (a provider, a magic link, a confirmation email) stores the step’s verifier. finish must run against the sign-in’s original store, or the call throws no_verifier. When the project requires verified addresses, signUp and addPasskey return no session until the address is confirmed.

Choose where the session lives with the store option. webStore() uses localStorage and follows a sign-in or sign-out made in another tab. memoryStore() lasts as long as the object. Any object with get and set also works, such as the Keychain or Keystore in a Flutter app. A session’s token lasts an hour and is renewed for you. A session that has ended or been signed out anywhere reads as signed out. In React, useSession(signIn) from napalm-client/react follows the session.

SignIn runs in a browser as is. On React Native, napalm-client/expo fills the gaps from Expo’s modules. secureStore(SecureStore) keeps the session in the Keychain or Keystore. Pass expoCrypto(Crypto) as the crypto option to supply the random bytes and SHA-256. The React Native guide builds an app with those two helpers.

Passkeys use the browser’s navigator.credentials in TypeScript. On a phone, pass a passkeys library as the passkeys option. In Dart, pass a Passkeys implementation backed by your platform’s passkey plugin. Refusals throw NapalmError (NapalmException in Dart) with a stable code: no_identity_found for a wrong address or password, verification_required, user_already_registered, verification_failed for a wrong or spent one-time 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 + secret at /sign-in/agents/token for a 60 s 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.

A handler takes a job’s long work on by returning accepted(). jobRun then sends word of the run: 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 SSE live queries

NapalmClient shares one POST /subscribe stream across every active query, applying commit-aligned id patches and dropping rows immediately on sign-out.

Persistent device sync stores

sync renders cached rows from IndexedDB or SQLite before the network answers, reconciles patches by id and resumes from the stored bookmark.

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' // One store for each synced query, made once.const notesStore = indexedDbSyncStore('notes') export function Notes() {  // The stored rows at once, then the project's.  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) keeps rows in the browser’s IndexedDB. On React Native, sqliteSyncStore(db, name) from napalm-client/expo keeps rows in expo-sqlite. memorySyncStore() keeps rows in memory. Outside React, napalm.sync takes the same query, variables and store, with onRows and onError handlers.

A count or another result without object ids is refused with ids_required. A refusal leaves the store unchanged. Every sync of one query with the same variables shares one subscription and one 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 the worker’s read sees the exact commit that fired the webhook. The guarantee holds on a replica too. (On Node 18 without global Web Crypto, pass { subtle: webcrypto.subtle } from node:crypto.)

The change log#

changes reads a branch’s committed rows from the change log through GET /changes, one page at a time. The caller’s access rules filter the rows. Each transaction’s rows carry a type, operation, id and values, and a gap marks each stretch the log cannot return. Start from a time with since, then pass each page’s next back as after. Delivery is at least once, so save the cursor after you handle a page, not before.

sync.ts
// Woken by a ping: read the log from where this reader stopped, up to what the ping spoke for.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)}

With reach, the reader stops once the log reaches that position, waiting briefly if needed. Paired with a ping webhook, you can tail the log without polling by reading up to each ping’s position. Without reach, the reader drains all available entries and stops, which fits scheduled catch-up jobs. To have committed rows pushed directly instead, attach a service key to the webhook so it delivers rows in order.

File uploads#

A query that sets a file’s size returns a file_upload once. upload takes that descriptor and the bytes and runs the rest of the upload lifecycle. A small file goes up in one signed PUT straight to object storage. A large file goes up four parts at a time, and part URLs are fetched as needed. Then POST /uploads/complete checks the size and reads the format from the first bytes. A PUT the store did not answer is tried again. The file’s ready state joins the client’s session, so a read right after the upload sees the file.

A stopped large upload resumes at the same point. Each part is sent with its SHA-256 digest, which object storage records. Calling upload again with the same file_upload and the same file sends only the parts the store does not hold. Keep the file_upload you received until the upload finishes.

upload.ts
const { data } = await db.POST('/query/addScan', {  body: { variables: { name: file.name, size: file.size } },})// One call sends the bytes, in parts when the file is large, and has them checked.const facts = await napalm.upload(data.data[0].file_upload, file, {  onProgress: (sent, total) => setProgress(sent / total),})// facts.format is 'Pdf', facts.content_type 'application/pdf'.

Bytes that a type’s rule refuses throw the rule’s message under not_accepted. The same file_upload accepts the right bytes until the descriptor expires. The bytes are a Blob, an ArrayBuffer, a typed array or an UploadSource. An upload source has a size and a read(start, end) for reading a file a stretch at a time. On React Native, fileSource from napalm-client/expo makes an upload source from a file on disk. The subtle option gives upload the phone’s SHA-256.

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
// The notes that best match, by meaning and by words, as the caller.const notes = await napalm.search<{ title: string }>('Note', 'plans for the launch', { limit: 5, fields: ['title'] }) // A question in words. One that needs a change comes back as the statement it would take, not run.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. A handler that answers JSON gives one frame named answer. An error frame ends the answer with a NapalmError (NapalmException in Dart), and a stream cut mid-flight ends with stream_ended. The stream’s bookmark merges into the client session so subsequent reads observe the handler’s writes.

summary.ts
// Each frame of the action's answer as the frame arrives. Leaving the loop early cuts the request.for await (const frame of napalm.streamAction('summarizeNote', { note: noteId })) {  if (typeof frame.json === 'string') summary += frame.json} // In React: the text so far, and a way to stop.const { text, isStreaming, error, call, stop } = useStreamedAction('summarizeNote')

In React, useStreamedAction(name) from napalm-client/react holds the text so far. The hook returns call to start an answer, stop to cut the answer short, isStreaming and error.

Type a word or two to search every docs page.