Skip to the page

Guides · Frameworks

React, Vite & single-page apps

Build a browser-direct React and Vite single-page app with PKCE sign-in, cross-tab sessions, generated live hooks, direct file uploads and deployed-query lockdown.

In the schema
ext::files::File

What you’ll build#

You will build and ship a browser-direct React and Vite single-page app that connects straight to a Napalm project URL with no custom backend server. Static HTML, JavaScript and CSS deploy to any CDN, Cloudflare Pages or object bucket while the browser handles PKCE sign-in, cross-tab session sync, generated live hooks, typed mutations and direct multipart file uploads.

Access policies compile directly into every SQL statement on the database engine, and --passthrough keys restricts browser sessions to your named deployed queries. Use the table below to choose between a browser-direct SPA and the server-rendered architecture in Next.js & React.

Static browser viewport

Your React and Vite bundle serves from any static CDN, holding PKCE sessions in webStore() and generated hooks with zero custom backend server.

Single HTTPS endpoint

The browser connects straight to <label>.napalmdata.com for /sign-in, /query/{name}, /subscribe and multipart /uploads.

Compiled access policies

Declarative schema policies compile into every SQL read, mutation and live subscription, keeping rows sealed by default.

ConcernBrowser-direct SPA (this guide)Server-rendered app (Next.js)
HostingStatic files on Cloudflare Pages, Vercel static output, S3 or any CDN.Server-rendered app (Next.js)Node or edge server running Route Handlers, Server Components and proxy.ts.
Session storagewebStore() in localStorage plus automatic cross-tab storage sync and Web Locks token renewal.Server-rendered app (Next.js)HttpOnly cookies unreadable by page scripts plus five-minute read-only pageToken() streams.
First paintStatic shell loads instantly from CDN cache and populates over /subscribe once the session loads.Server-rendered app (Next.js)Server Components query Napalm during SSR and send populated HTML on the first response.
Mutations and uploadsdb.POST and napalm.upload run straight from the browser against the project endpoint and bucket.Server-rendered app (Next.js)Mutations run through Server Actions while file bytes still upload straight from the browser.
Third-party secretsKept out of the bundle by attaching an action handler (napalm actions add) or background job.Server-rendered app (Next.js)Read inside Server Actions, Route Handlers or action handlers.

RFC 10017 recommends server-held HttpOnly cookies when defending against script injection is paramount because any script running on your origin can read localStorage. When you deploy a static SPA, pair webStore() with --passthrough keys and a strict Content-Security-Policy.

Set up the client and generated hooks#

Start from a project running the schema from Your first app. Enable the project HTTP endpoint for Vite’s local origin, install napalm-client alongside openapi-fetch and generate TypeScript bindings from your deployed queries.

Terminal
napalm endpoint notes --enable --allow-origin http://localhost:5173echo "VITE_NAPALM_URL=https://<project-address>" > .env.local npm install napalm-client openapi-fetchnapalm queries push notesnapalm generate notes --deployed --lang ts -o src/napalm

Lock Vite’s dev server to port 5173 so it never silently increments the port and breaks the browser origin check.

vite.config.ts
// vite.config.tsimport react from '@vitejs/plugin-react'import { defineConfig } from 'vite' // Keep port 5173 fixed so the browser Origin header always matches --allow-origin.export default defineConfig({  plugins: [react()],  server: { port: 5173, strictPort: true },})

Because react is present in package.json, napalm generate writes schema.ts (OpenAPI request and row types), live.ts (live query descriptors and RowOf helpers) and hooks.ts (one React hook per read query). Wire SignIn, NapalmClient and createClient<paths> once in src/lib/napalm.ts and provide the client at the root.

src/lib/napalm.ts
// src/lib/napalm.tsimport createClient from 'openapi-fetch'import { NapalmClient, SignIn, webStore } from 'napalm-client'import type { paths } from '../napalm/schema' export const address = import.meta.env.VITE_NAPALM_URL as string /** Browser session store backed by localStorage, Web Locks and cross-tab storage events. */export const signIn = new SignIn(address, { store: webStore() }) /** Multiplexes live queries over one SSE stream and clears active rows when the caller changes. */export const napalm = new NapalmClient(address, { signIn }) /** Typed deployed query caller that sends the current bearer token and Napalm-Bookmark. */export const db = createClient<paths>({ baseUrl: address, fetch: napalm.fetch })
src/main.tsx
// src/main.tsximport { NapalmProvider } from 'napalm-client/react'import { StrictMode } from 'react'import { createRoot } from 'react-dom/client'import { App } from './App'import { napalm } from './lib/napalm' createRoot(document.getElementById('root')!).render(  <StrictMode>    <NapalmProvider client={napalm}>      <App />    </NapalmProvider>  </StrictMode>,)

Browser-direct SPA client

The static bundle stores PKCE sessions in webStore() with navigator.locks token renewal, multiplexes live hooks onto one POST /subscribe SSE stream and chains Napalm-Bookmark across replica reads.

Account switching
NapalmClient subscribes to signIn.onChange. Signing out or switching accounts drops all cached live rows immediately and reconnects as the new caller, so one user’s rows never linger on screen.
Cross-tab renewal
webStore() watches browser storage events across open tabs and serializes hourly refresh token trades through navigator.locks. Two tabs never spend the same single-use refresh token.
Causal replica reads
napalm.fetch records the highest Napalm-Bookmark across every db.POST mutation and live frame, then sends that header on subsequent reads so replicas always include the tab’s own writes. See Causal bookmarks.
Personal dev branches
During feature work, point VITE_NAPALM_URL at https://<project-address>/branches/dev-ada and run napalm generate notes --lang ts --branch dev-ada -o src/napalm. Undeployed branch clients send the query text alongside variables.

Sign people in from the browser#

Configure your allowed return URLs and sign-in providers on the project. Every flow in SignIn runs PKCE in the browser using Web Crypto SHA-256 challenges and stores the verifier in webStore() across redirects.

Terminal
napalm sign-in set notes --app-name Notes --email-password \  --redirect https://app.example.com/signed-in \  --redirect http://localhost:5173/signed-innapalm sign-in provider notes github --client-id <client-id>napalm sign-in provider notes magicLink --auto-signupnapalm sign-in provider notes passkeys --origin https://app.example.com

Track the active caller with useSession(signIn) from napalm-client/react. The hook returns undefined until localStorage is read, null when nobody is signed in and the Session once authenticated.

src/App.tsx
// src/App.tsximport { useSession } from 'napalm-client/react'import { signIn } from './lib/napalm'import { NotesWorkspace } from './NotesWorkspace'import { SignedInCallback } from './SignedInCallback'import { SignInScreen } from './SignInScreen' export function App() {  const session = useSession(signIn)  if (location.pathname === '/signed-in') return <SignedInCallback />  // Wait for localStorage before picking a screen so signed-in reloads never flash the form.  if (session === undefined) return null  if (session === null) return <SignInScreen />   return (    <main>      <header>        <span>Signed in as {session.identity_id}</span>        <button onClick={() => void signIn.signOut()}>Sign out</button>      </header>      <NotesWorkspace />    </main>  )}

Call signIn.metadata() to render the app’s configured name and enabled OAuth or OpenID Connect providers dynamically alongside password, passkey and magic-code options.

src/SignInScreen.tsx
// src/SignInScreen.tsximport { NapalmError, type SignInMetadata } from 'napalm-client'import { useEffect, useState } from 'react'import { signIn } from './lib/napalm' export function SignInScreen() {  const [meta, setMeta] = useState<SignInMetadata>()  const [email, setEmail] = useState('')  const [password, setPassword] = useState('')  const [code, setCode] = useState('')  const [awaitingCode, setAwaitingCode] = useState(false)  const [problem, setProblem] = useState<string>()   useEffect(() => {    void signIn.metadata().then(setMeta)  }, [])   const run = async (step: () => Promise<unknown>) => {    setProblem(undefined)    try {      await step()    } catch (error) {      const wrongLogin = error instanceof NapalmError && error.code === 'no_identity_found'      setProblem(wrongLogin ? 'Wrong email address or password.' : error instanceof Error ? error.message : String(error))    }  }   const oauth = meta?.providers.filter((p) => p.name.startsWith('builtin::oauth_') || p.name.startsWith('oidc::'))   return (    <section>      <h1>{meta?.app_name ?? 'Sign in'}</h1>      <form onSubmit={(e) => { e.preventDefault(); void run(() => signIn.withPassword(email, password)) }}>        <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="Email" required />        <input type="password" value={password} onChange={(e) => setPassword(e.target.value)} placeholder="Password" required />        <button type="submit">Sign in</button>      </form>      <button type="button" onClick={() => void run(() => signIn.withPasskey(email))}>Sign in with passkey</button>      {!awaitingCode ? (        <button          type="button"          onClick={() => void run(async () => {            const sent = await signIn.sendCode(email, {              callbackUrl: `${location.origin}/signed-in`,              redirectOnFailure: location.origin,            })            setAwaitingCode(sent.isCode)          })}        >          Email a sign-in code        </button>      ) : (        <form onSubmit={(e) => { e.preventDefault(); void run(() => signIn.withCode(email, code)) }}>          <input value={code} onChange={(e) => setCode(e.target.value)} placeholder="6-digit code" required />          <button type="submit">Verify code</button>        </form>      )}      {oauth?.map((provider) => (        <button          key={provider.name}          type="button"          onClick={() => void run(async () => {            location.assign(await signIn.providerUrl(provider.name, { redirectTo: `${location.origin}/signed-in` }))          })}        >          Continue with {provider.display_name ?? provider.name}        </button>      ))}      {problem && <p role="alert">{problem}</p>}    </section>  )}

Complete redirects on the callback route#

OAuth providers, clicked magic links and email verification links return the browser to /signed-in. Call signIn.finish() on mount to exchange the returned code or verification_token with the stored PKCE verifier and replace the history entry.

src/SignedInCallback.tsx
// src/SignedInCallback.tsximport { useEffect, useState } from 'react'import { signIn } from './lib/napalm' export function SignedInCallback() {  const [problem, setProblem] = useState<string>()  useEffect(() => {    void signIn      .finish()      .then(() => location.replace('/'))      .catch((error: unknown) => setProblem(error instanceof Error ? error.message : String(error)))  }, [])  return problem ? <p role="alert">{problem}</p> : <p>Completing sign-in…</p>}

Subscribe to live queries and run mutations#

Every read query in dbschema/queries/ compiles into a React hook in src/napalm/hooks.ts, and every write query compiles into a typed POST /query/{name} path on db. The workspace below pairs myNotes.edgeql and addNote.edgeql from the starter app with a parameterized prefix query.

Multiplexed live subscription stream

Every active live hook in the tab shares one POST /subscribe Server-Sent Events connection so lists and filtered views advance on the same commit frame.

dbschema/queries/myNotes.edgeql
# The caller's notes. The rule decides whose they are: the query doesn't say.select Note { id, title, body }order by .title
dbschema/queries/addNote.edgeql
insert Note {  owner := global caller,  title := <str>$title,  body := <str>$body,}
src/NotesWorkspace.tsx
// src/NotesWorkspace.tsximport { useState, type FormEvent } from 'react'import { db } from './lib/napalm'import { useMyNotes, useTitlesStarting } from './napalm/hooks' export function NotesWorkspace() {  const [prefix, setPrefix] = useState('')  const [title, setTitle] = useState('')  const [body, setBody] = useState('')  const [pendingTitles, setPendingTitles] = useState<string[]>([])  const [problem, setProblem] = useState<string>()   // Both hooks share one POST /subscribe SSE stream. The second hook pauses while prefix is empty.  const { rows, changes, error, isLoading } = useMyNotes()  const filtered = useTitlesStarting({ start: prefix }, { isPaused: prefix.length === 0 })   const updatedIds = new Set(changes.filter((change) => change.type === 'update').map((change) => change.id))  const committed = new Set(rows?.map((note) => note.title))  const waiting = pendingTitles.filter((pending) => !committed.has(pending))   const createNote = async (event: FormEvent) => {    event.preventDefault()    const nextTitle = title.trim()    if (!nextTitle) return    setProblem(undefined)    setPendingTitles((current) => [...current, nextTitle])    setTitle('')    setBody('')     const { error: callError } = await db.POST('/query/addNote', {      body: { variables: { title: nextTitle, body } },    })    if (callError) {      setPendingTitles((current) => current.filter((saved) => saved !== nextTitle))      setProblem(callError.error.message ?? callError.error.code)    }  }   return (    <section>      <form onSubmit={(e) => void createNote(e)}>        <input value={title} onChange={(e) => setTitle(e.target.value)} placeholder="Title" required />        <input value={body} onChange={(e) => setBody(e.target.value)} placeholder="Body" required />        <button type="submit">Save note</button>      </form>      <input value={prefix} onChange={(e) => setPrefix(e.target.value)} placeholder="Filter titles by prefix…" />      {(problem ?? error?.message) && <p role="alert">{problem ?? error?.message}</p>}      {isLoading ? (        <p>Loading notes…</p>      ) : (        <ul>          {waiting.map((pending) => <li key={`pending-${pending}`} aria-busy="true">{pending}</li>)}          {(prefix ? filtered.rows : rows)?.map((note) => (            <li key={note.id} data-updated={updatedIds.has(note.id) || undefined}>{note.title}</li>          ))}        </ul>      )}    </section>  )}
Single SSE connection
All mounted hooks share one POST /subscribe stream. Every active query advances at the same commit cut, and a project supports up to 1,000 concurrent live subscriptions for each GiB of engine memory (429 live_limit_reached beyond that limit).
Pausing hidden views
Pass { isPaused: true } for unmounted drawers, collapsed panels or empty filter inputs. Pausing unsubscribes the query on the shared stream while retaining the last rows in memory.
Optimistic state
Keep pending UI entries visible until rows reflects the commit rather than clearing state when db.POST resolves. Holding the entry prevents a single-frame flash when the HTTP response arrives ahead of the SSE patch. Realtime & collaboration demonstrates fractional-index drag ordering and versioned conflict checks.
Structured refusals
db.POST returns { data, error } without throwing on 4xx or 5xx responses and exposes error.error.code plus error.error.message. Live stream errors surface on the hook’s error field as NapalmError instances.

Upload files straight from the browser#

Browser apps upload files directly to object storage without routing bytes through a backend server. First call a deployed mutation that sets file_size on a type extending ext::files::File to obtain a single-use file_upload plan, then pass the browser File object straight to napalm.upload.

dbschema/queries/addFile.edgeql
# The query that sets a file's size is the one given its upload.select (insert Attachment {  owner := global caller,  file_name := <str>$name,  file_size := <int64>$size,}) { id, file_upload }
src/AttachmentUploader.tsx
// src/AttachmentUploader.tsximport { NapalmError, type FileUpload } from 'napalm-client'import { useRef, useState, type ChangeEvent } from 'react'import { db, napalm } from './lib/napalm'import { useMyFiles } from './napalm/hooks' export function AttachmentUploader() {  const { rows } = useMyFiles()  const [progress, setProgress] = useState<number>()  const [problem, setProblem] = useState<string>()  const abortRef = useRef<AbortController | null>(null)   const handleFile = async (event: ChangeEvent<HTMLInputElement>) => {    const file = event.target.files?.[0]    if (!file) return    setProblem(undefined)    const controller = new AbortController()    abortRef.current = controller     try {      // Insert the Attachment row with file_size to receive a one-time upload plan.      const { data, error } = await db.POST('/query/addFile', {        body: { variables: { name: file.name, size: file.size } },        signal: controller.signal,      })      if (error) throw new Error(error.error.message ?? error.error.code)       // Stream bytes straight from the browser to object storage and verify magic bytes.      await napalm.upload(data.data[0].file_upload as FileUpload, file, {        signal: controller.signal,        onProgress: (sent, total) => setProgress(sent / total),      })    } catch (error) {      if (error instanceof NapalmError && error.code === 'not_accepted') {        setProblem(`Rejected file format: ${error.message}`)      } else if (!controller.signal.aborted) {        setProblem(error instanceof Error ? error.message : String(error))      }    } finally {      setProgress(undefined)      abortRef.current = null      event.target.value = ''    }  }   return (    <section>      <input type="file" onChange={(e) => void handleFile(e)} />      {progress !== undefined && (        <>          <progress value={progress} max={1} />          <button type="button" onClick={() => abortRef.current?.abort()}>Cancel</button>        </>      )}      {problem && <p role="alert">{problem}</p>}      <ul>        {rows?.map((file) => (          <li key={file.id}>            {file.file_download_url ? <a href={file.file_download_url}>{file.file_name}</a> : file.file_name}          </li>        ))}      </ul>    </section>  )}
Multipart and resume
Small files upload in one signed PUT, and large files split into parts uploaded four at a time with Web Crypto SHA-256 digests. Calling napalm.upload again with the same file_upload plan and File after a network drop skips parts already stored.
Magic-byte verification
POST /uploads/complete inspects the stored bytes before marking the row Ready. Schema format constraints that fail reject the upload with 409 not_accepted and delete the unverified object.
Immediate visibility
Completion advances napalm’s causal bookmark and triggers live query patches on useMyFiles(), so presigned file_url and file_download_url links appear without manual polling.

Files & object storage covers public buckets, custom asset domains and presigned URL caching windows.

Lock down origins and passthrough for launch#

Because a single-page app ships every client line to the browser, production security relies on database access policies paired with strict endpoint lockdown rather than obscurity in frontend code. Run these five commands before opening the app to real users.

Endpoint origin & deployed-query lockdown

Combining --allow-origin, --passthrough keys and --hide-schema confines browser tokens to named /query/{name} and /subscribe routes while rejecting ad-hoc EdgeQL strings with 403 deployed_query_required.

Terminal
napalm queries push notesnapalm endpoint notes --allow-origin https://app.example.com --remove-origin http://localhost:5173napalm endpoint notes --passthrough keys --hide-schemanapalm sign-in set notes --redirect https://app.example.com/signed-in --require-verificationnapalm status notes
--allow-origin
A branch allows up to 32 exact browser origins (scheme, host and port). Requests from unlisted origins receive 403 forbidden and no CORS headers. Remove http://localhost:5173 on main.
--passthrough keys
Browser sessions can invoke only named deployed queries (/query/{name} and /subscribe by query name). Any ad-hoc EdgeQL call (POST /query) from a user session fails with 403 deployed_query_required.
--hide-schema
Blocks GET /schema, POST /ask and MCP schema inspection for callers unless your app intentionally exposes natural-language questions.
CSP and session lifetime
Serve a Content-Security-Policy header from your static host with script-src 'self' and connect-src 'self' https://<project-address> plus your cluster’s storage domain. Sessions last 14 days by default (--session-hours), and signOut() revokes stolen tokens on the server immediately.

Call third-party APIs without adding a custom server#

Never place a Napalm service key (ndb_…) or a third-party secret such as STRIPE_SECRET_KEY or RESEND_API_KEY inside VITE_* environment variables because Vite inlines every VITE_* value into the public JavaScript bundle. Attach an action to a deployed gatekeeper query instead.

Terminal
napalm actions add notes createCheckout https://actions.example.com/actions/createCheckout \  --answer-schema checkout-answer.jsonnapalm generate notes --deployed --lang ts -o src/napalm

When the browser calls db.POST('/query/createCheckout'), Napalm runs the gatekeeper query as the signed-in user first, returns 403 nothing_found when access rules match zero rows and otherwise forwards a signed assertion to a small stateless edge worker running handleCalls (or queueing an ext::napalm::Job in the same commit). Actions & background jobs walks through the complete pattern.

Check browser security and live sync#

  1. Verify live sync and cross-tab sign-out

    Open the deployed app in two browser tabs, sign in and save a note in the first tab. Confirm the note appears in the second tab over the open /subscribe stream without a reload. Click sign-out in the first tab and confirm the second tab clears the note list and returns to the sign-in screen immediately.

  2. Confirm ad-hoc EdgeQL is refused

    With --passthrough keys enabled, send a raw POST /query request from the browser console using the session’s bearer token. Confirm the project responds with 403 deployed_query_required while POST /query/myNotes continues to succeed.

  3. Confirm unlisted origins are rejected

    Start a local server on an unlisted port (npx vite --port 5174) pointed at main. Confirm the browser blocks the request and napalm endpoint notes lists only your production HTTPS origin.

  4. Audit project status

    Run napalm status notes and verify that the API, access policies, sign-in, deployed queries and file buckets all report on.

Next steps#

Next.js & React
Move sessions into HttpOnly server cookies with Server Components and five-minute read-only page tokens.
Sign-in for your app
Add password resets, email verification flows, enterprise OIDC providers and passkey enrollment.
Realtime & collaboration
Add shared editing, fractional drag-and-drop ordering, optimistic version checks and active viewers.
Actions & background jobs
Run Stripe charges, transactional emails and scheduled jobs under the caller’s access policies.
Environments & going live
Set up personal dev branches, automatic pull-request preview branches and zero-downtime migrations.

Type a word or two to search every docs page.