Skip to the page

Guides · Frameworks

React Native

Build an Expo app that stores the session in the phone’s Keychain, streams a live list while open and uploads files from disk.

In the schema
ext::files::File

What you’ll build#

This page moves the notes app from Your first app onto a phone as an Expo app in TypeScript using the same client library and generated hooks as the web app. People sign in with a password or OAuth provider, saved notes stay live while the app is in the foreground, local SQLite keeps cached rows available without signal and files upload directly from disk in chunks.

Every read, write and offline sync runs under your schema’s policies inside PostgreSQL, so a phone caches only rows the signed-in person owns. Because React Native has no browser globals, napalm-client/expo supplies native adapters for storage and cryptography while SignIn, NapalmClient, useSession and generated live hooks stay identical across web and mobile.

Shared generated hooks & Expo adapters

napalm-client/expo pairs native Keychain and SHA-256 adapters with the exact hooks.ts and openapi-fetch client used on the web.

SQLite row mirror & resumable uploads

expo-sqlite renders cached rows on offline launches before POST /subscribe resumes from napalm.bookmark, and fileSource streams chunks from disk.

Client capabilityIn a browserOn a phone
Session storagewebStore()On a phoneKeychain or Keystore via secureStore(SecureStore)
Random bytes and SHA-256cryptoOn a phoneexpo-crypto via expoCrypto(Crypto)
Typed calls and live hooksnapalm generate --lang tsOn a phoneIdentical openapi-fetch client and hooks.ts
Offline row mirrorIndexedDB or OPFS SQLiteOn a phoneexpo-sqlite wiped on signIn.onChange
File bytesBrowser File inputOn a phoneStreamed disk chunks via fileSource(file)
Provider callbackHTTPS web callback URLOn a phoneCustom reverse-DNS scheme or Universal / App Link
Passkeysnavigator.credentialsOn a phoneNative passkey module passed as passkeys

The samples target Expo SDK 58 and React Native 0.88. Bare React Native apps without Expo modules pass SignIn a two-method store and crypto object directly.

Before you start#

Start from the project created in Your first app with deployed queries pushed and email-and-password sign-in enabled. Scaffold an Expo app, install the native adapters and generate your typed client and React hooks.

Terminal
npx create-expo-app@latest notes-phone --template blank-typescriptcd notes-phonenpx expo install expo-crypto expo-secure-store expo-web-browser expo-file-system expo-sqlitenpm install napalm-client openapi-fetch # Generate typed query calls and live React hooks from your deployed queriesnapalm queries push notesnapalm generate notes --deployed --lang ts -o src/napalm # Print the project's HTTPS address and write .envecho "EXPO_PUBLIC_NAPALM_URL=https://<project-address>" > .env

Native phone requests carry no browser Origin header, so the project’s CORS origin allowlist does not apply to mobile traffic and --allow-origin is needed only for browser clients.

Set up the client and generated hooks#

Wire SignIn, NapalmClient and the generated openapi-fetch client in one module. Passing napalm.fetch into createClient<paths> attaches the active bearer token and advances Napalm-Bookmark across every deployed query call and live subscription.

src/lib/napalm.ts
// src/lib/napalm.tsimport * as Crypto from 'expo-crypto'import * as SecureStore from 'expo-secure-store'import createClient from 'openapi-fetch'import { NapalmClient, SignIn } from 'napalm-client'import { expoCrypto, secureStore } from 'napalm-client/expo'import type { paths } from '../napalm/schema' /** Project HTTPS address read from .env at build time. */export const address = process.env.EXPO_PUBLIC_NAPALM_URL as string /** Native random bytes and SHA-256 for PKCE sign-in and resumable multipart uploads. */export const crypto = expoCrypto(Crypto) /** Session store backed by Keychain on iOS and Keystore on Android. */export const signIn = new SignIn(address, { store: secureStore(SecureStore), crypto }) /** Multiplexes live queries and restarts subscriptions automatically when the caller changes. */export const napalm = new NapalmClient(address, { signIn }) /** Typed deployed-query client that attaches the active bearer token and Napalm-Bookmark. */export const db = createClient<paths>({ baseUrl: address, fetch: napalm.fetch })
secureStore(SecureStore)
Persists the session and PKCE verifier under keys prefixed napalm.. Pass a second string argument to customize the key prefix.
expoCrypto(Crypto)
Supplies secure random bytes for PKCE verifiers and native SHA-256 digests for resumable multipart uploads.
Generated hooks
napalm generate notes --deployed --lang ts -o src/napalm writes schema.d.ts for openapi-fetch alongside hooks.ts (useMyNotes, useMyFiles). TypeScript documents every generated export.

Sign people in#

Project sign-in returns a bearer session rather than a browser cookie, so native apps authenticate without an embedded web view. useSession reads Keychain or Keystore on cold launch and updates the root view on every sign-in and sign-out.

App.tsx
// App.tsximport { NapalmProvider, useSession } from 'napalm-client/react'import { napalm, signIn } from './src/lib/napalm'import { NotesScreen } from './src/NotesScreen'import { SignInPage } from './src/SignInPage' export default function App() {  // Undefined while Keychain loads, null when signed out, or the active Session.  const session = useSession(signIn)  return (    <NapalmProvider client={napalm}>      {session === undefined ? null : session ? <NotesScreen /> : <SignInPage />}    </NapalmProvider>  )}
src/SignInPage.tsx
// src/SignInPage.tsximport { NapalmError } from 'napalm-client'import { useState } from 'react'import { Button, Text, TextInput, View } from 'react-native'import { signIn } from './lib/napalm'import { signInWith } from './signInWith' export function SignInPage() {  const [email, setEmail] = useState('')  const [password, setPassword] = useState('')  const [problem, setProblem] = useState('')   // Each sign-in flow writes the new session to Keychain so useSession switches screens.  const attempt = async (flow: () => Promise<unknown>) => {    try {      setProblem('')      await flow()    } catch (error) {      const isWrong = error instanceof NapalmError && error.code === 'no_identity_found'      setProblem(isWrong ? 'Wrong email or password.' : `${error instanceof Error ? error.message : error}`)    }  }   return (    <View style={{ gap: 12, padding: 24, paddingTop: 96 }}>      <TextInput placeholder="Email" autoCapitalize="none" keyboardType="email-address" onChangeText={setEmail} />      <TextInput placeholder="Password" secureTextEntry onChangeText={setPassword} />      <Button title="Sign in" onPress={() => void attempt(() => signIn.withPassword(email, password))} />      <Button title="Continue with Google" onPress={() => void attempt(() => signInWith('builtin::oauth_google'))} />      <Text accessibilityRole="alert">{problem}</Text>    </View>  )}

Access tokens last an hour. SignIn refreshes expiring tokens in the background and writes the updated session back to secure storage. Sign-in for your app covers sign-up, six-digit magic-link codes, password resets and session duration.

OAuth providers and deep links#

OAuth providers open in the system browser (ASWebAuthenticationSession on iOS and Custom Tabs on Android) and redirect back to your app. Register both a reverse-DNS custom scheme and, when you own a web domain, iOS Universal Links and Android App Links in app.json and in the project’s redirect allowlist.

app.json
{  "expo": {    "scheme": "com.example.notes",    "ios": {      "associatedDomains": ["applinks:app.example.com", "webcredentials:app.example.com"]    },    "android": {      "intentFilters": [        {          "action": "VIEW",          "autoVerify": true,          "data": [{ "scheme": "https", "host": "app.example.com", "pathPrefix": "/signed-in" }],          "category": ["BROWSABLE", "DEFAULT"]        }      ]    }  }}
Terminal
# Each --redirect invocation replaces the redirect allowlist, so list mobile and web callbacks together.napalm sign-in set notes \  --redirect com.example.notes://signed-in \  --redirect https://app.example.com/signed-in \  --redirect http://localhost:5173/signed-in
src/signInWith.ts
// src/signInWith.tsimport * as WebBrowser from 'expo-web-browser'import { signIn } from './lib/napalm' /** Custom reverse-DNS callback registered in app.json and napalm sign-in set. */const redirectTo = 'com.example.notes://signed-in' /** Opens an OAuth provider such as builtin::oauth_google in the system browser. */export async function signInWith(provider: string) {  const url = await signIn.providerUrl(provider, { redirectTo })  // Uses ASWebAuthenticationSession on iOS and Custom Tabs on Android rather than an embedded web view.  const returned = await WebBrowser.openAuthSessionAsync(url, redirectTo)  // Exchanges the returned authorization code with the PKCE verifier kept in Keychain.  return returned.type === 'success' ? signIn.finish(returned.url) : null}
Reversed domain
Custom schemes must contain a dot, such as com.example.notes. The redirect allowlist rejects single-word schemes like notes://.
PKCE protection
The returned authorization code works only with the PKCE verifier stored inside Keychain or Keystore, and Universal Links or App Links bind HTTPS callbacks directly to your signed app bundle.
Development builds
Expo Go registers only exp:// URLs. Test OAuth redirects and Universal Links in a development build (npx expo run:ios or npx expo run:android). Email passwords and typed magic-link codes work inside Expo Go.

Passkeys#

Pass a native WebAuthn bridge such as react-native-passkey into SignIn as passkeys. signIn.addPasskey and signIn.withPasskey then accept and return standard WebAuthn JSON just like in a browser.

src/lib/napalm.ts
// src/lib/napalm.ts: add the native passkeys adapterimport { Passkey } from 'react-native-passkey' export const signIn = new SignIn(address, {  store: secureStore(SecureStore),  crypto,  passkeys: Passkey,})

Keep a list live in the foreground#

Generated hooks such as useMyNotes subscribe over one shared SSE connection. Mobile operating systems reclaim background sockets shortly after the person switches apps, so pass isPaused from AppState to release the stream in the background and resume cleanly in the foreground.

src/NotesScreen.tsx
// src/NotesScreen.tsximport { useEffect, useState } from 'react'import { AppState, Button, FlatList, Text, TextInput, View } from 'react-native'import { db, signIn } from './lib/napalm'import { useMyNotes } from './napalm/hooks' /** Tracks whether the operating system moved the app into the background. */function useIsInBackground() {  const [isInBackground, setIsInBackground] = useState(AppState.currentState === 'background')  useEffect(() => {    const subscription = AppState.addEventListener('change', (state) => setIsInBackground(state === 'background'))    return () => subscription.remove()  }, [])  return isInBackground} export function NotesScreen() {  // Releases the SSE socket in the background and resumes from napalm.bookmark on foregrounding.  const { rows, error } = useMyNotes({ isPaused: useIsInBackground() })  const [title, setTitle] = useState('')  const [problem, setProblem] = useState<string>()   const add = async () => {    const trimmed = title.trim()    if (!trimmed) return    setProblem(undefined)    const { error: callError } = await db.POST('/query/addNote', {      body: { variables: { title: trimmed, body: 'From my phone' } },    })    if (callError) {      setProblem(callError.error.message ?? callError.error.code)      return    }    setTitle('')  }   return (    <View style={{ flex: 1, gap: 12, padding: 24, paddingVertical: 96 }}>      <TextInput placeholder="A new note" value={title} onChangeText={setTitle} onSubmitEditing={() => void add()} />      {(problem ?? error?.message) && <Text accessibilityRole="alert">{problem ?? error?.message}</Text>}      <FlatList        data={rows ?? []}        keyExtractor={(note) => note.id}        renderItem={({ item }) => (          <Text>            {item.title}: {item.body}          </Text>        )}      />      <Button title="Sign out" onPress={() => void signIn.signOut()} />    </View>  )}
isPaused
Closes the SSE stream once all active hooks pause while keeping the last rows on screen. Foregrounding reopens the subscription from napalm.bookmark so the list never flashes an older snapshot.
Lost connections
The server sends a heartbeat every 15 seconds. After 35 seconds of silence or a Wi-Fi-to-cellular handoff drop, NapalmClient reconnects with jittered backoff and preserves visible rows.
Active viewers
usePresence accepts the same isPaused flag so backgrounded phones leave the room promptly. Realtime & collaboration builds a shared room view.

Cache rows offline with SQLite#

In-memory live hooks start empty when an app cold-launches in a subway or on a plane. useSyncedQuery mirrors myNotes into expo-sqlite so the screen renders cached notes immediately on startup, and once connectivity returns the project streams only changes after the stored bookmark instead of resending the full list. Clear the local table inside signIn.onChange so signing out wipes cached data from disk.

src/offlineNotes.ts
// src/offlineNotes.tsimport { deployed } from 'napalm-client'import { sqliteSyncStore } from 'napalm-client/expo'import { useSyncedQuery } from 'napalm-client/react'import * as SQLite from 'expo-sqlite'import { signIn } from './lib/napalm' export type CachedNote = { id: string; title: string; body: string } const myNotes = deployed<CachedNote>('myNotes')const localDb = SQLite.openDatabaseSync('notes-cache.db')// The rows of myNotes and the bookmark they stand at, in two tables the store makes.const notesStore = sqliteSyncStore(localDb, 'notes') // An open sync clears the store when the person changes. Clearing here covers a store no screen holds open.signIn.onChange((session) => {  if (session === null) void notesStore.clear()}) export function useCachedNotes(isPaused: boolean) {  // The stored rows at once, then the changes since their bookmark once the radio connects.  const { rows, isStored, error } = useSyncedQuery(myNotes, {}, notesStore, { isPaused })  return { rows, isLive: rows !== undefined && !isStored, error }}

For apps that also create, edit and archive records without a network connection, pair SQLite mirror tables with an idempotent mutation outbox and version conflict checks in Offline caches & reconnect sync.

Upload a file from the phone#

Running addFile with a byte size returns a presigned file_upload descriptor. On a phone, fileSource streams chunks straight from the picker or camera URI to object storage without buffering the whole file in JavaScript memory.

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/attach.ts
// src/attach.tsimport { File } from 'expo-file-system'import type { FileUpload } from 'napalm-client'import { fileSource } from 'napalm-client/expo'import { crypto, db, napalm } from './lib/napalm' /** Streams a file from phone storage in chunks and reports byte progress. */export async function attach(uri: string, onProgress: (fraction: number) => void) {  const file = new File(uri)  // Setting size in addFile opens a presigned file_upload session on the returned row.  const { data, error } = await db.POST('/query/addFile', {    body: { variables: { name: file.name, size: file.size } },  })  if (error || !data?.data[0]) {    throw new Error(error?.error.message ?? error?.error.code ?? 'Upload initialization failed')  }  const created = data.data[0] as { id: string; file_upload: FileUpload }  // Reads one byte range from disk at a time so large camera videos never fill memory.  await napalm.upload(created.file_upload, fileSource(file), {    // Native SHA-256 lets interrupted uploads skip parts that object storage already holds.    subtle: crypto.subtle,    onProgress: (sent, total) => onProgress(sent / total),  })  return created.id}
Bounded memory
Large videos upload four parts at a time. Only active chunks occupy RAM, and onProgress reports confirmed byte totals.
Resuming interrupted uploads
Persist created.file_upload across retries and pass subtle: crypto.subtle. napalm.upload hashes each part with SHA-256 and skips parts that object storage already verified.
In-memory thumbnails
Pass a Uint8Array or ArrayBuffer directly instead of fileSource(file) when uploading resized images already in memory.

Files & object storage and Files, media & document search cover MIME verification, magic-byte constraints and background document indexing.

Check the app in Expo#

Run npx expo start and open the app on a simulator or physical phone.

  1. Sign in and cold-restart in airplane mode

    Sign in once while online so Keychain stores the session and expo-sqlite caches your notes. Quit the app, turn on airplane mode and relaunch. Your cached notes render immediately without a sign-in prompt.

  2. Add a note in the web app

    Disable airplane mode and add a note from the browser as the same person. The phone updates within a second without pull-to-refresh.

  3. Background the app and add another note

    Move the phone app to the home screen, add a note on the web and bring the phone app back. The resumed stream advances from napalm.bookmark and displays the new note immediately.

  4. Interrupt a large upload mid-flight

    Enable airplane mode halfway through attach(). napalm.upload retries three times and throws upload_failed. Re-enable connectivity and call napalm.upload with the saved file_upload descriptor to resume from the last verified part.

  5. Sign out and switch accounts

    Tap Sign out and sign in as a second user. signIn.onChange clears cached_notes, and the schema policy on Note serves only the second user’s rows.

Next steps#

Offline caches & reconnect sync
Queue offline mutations in SQLite with idempotent UUIDs, row version checks and conflict recovery.
Environments & going live
Lock --passthrough none and test mobile builds against isolated pull-request branches before launch.
Email, Slack & push
Deliver APNs and FCM push notifications from committed database writes through actions or webhooks.

Type a word or two to search every docs page.