Mobile apps
Build an iOS and Android client for a DeepSpace app with Expo and deepspace/native.
On this page
A DeepSpace app can have a native mobile client built with Expo (React Native). The client talks to the same Worker as the website, so it reads the same records under the same permissions, calls the same integrations and server actions, and signs in to the same accounts. Mobile support requires deepspace 0.39 or later and Expo SDK 57; use 0.39.2 or later so that signing out also ends the session on the server.
Add a mobile client#
From the app directory:
npx deepspace add mobile
This writes an Expo project to mobile/. Its package.json pins the same deepspace version as the app, and mobile/app.config.ts reads the app id and app.space name from wrangler.toml, so the client always points at the app it belongs to. Nothing in the website changes; the linter is told to skip mobile/.
The client signs in through a custom URL scheme: the app name with the dashes removed (my-app becomes myapp). Allowlist its callback in wrangler.toml and deploy the Worker:
[vars]
NATIVE_AUTH_REDIRECT_URIS = "myapp://auth/callback"
Until the callback is listed, mobile/app.config.ts stops the build and prints the exact line to add. List several callbacks separated by commas; the Worker accepts only exact matches.
Then run the app in the iOS Simulator or an Android emulator:
cd mobile
npm install
npx expo run:ios # or: npx expo run:android
Sign-in#
Create one client at module scope and render one DeepSpaceNativeProvider at the root. useDeepSpace returns the auth state with signIn and signOut:
import { createDeepSpaceExpoClient, DeepSpaceNativeProvider, useDeepSpace } from 'deepspace/native'
const deepSpace = createDeepSpaceExpoClient({ baseUrl: 'https://my-app.app.space' })
export default function App() {
return (
<DeepSpaceNativeProvider client={deepSpace}>
<Root />
</DeepSpaceNativeProvider>
)
}
function Root() {
const { isLoaded, isSignedIn, signIn } = useDeepSpace()
if (!isLoaded) return null
if (!isSignedIn) return <SignInButton onPress={() => signIn('google')} />
return <Home />
}
signIn opens the provider's sign-in page in the system browser. The Worker returns a one-time code to the app's callback, and the app redeems it with a PKCE verifier that it sends straight to the Worker, never through the browser or the callback URL, so another app that intercepts the callback cannot use the code. The long-lived session is stored in the device keychain (Expo SecureStore); requests carry a short-lived token that the client refreshes shortly before it expires. A network failure during refresh keeps the session; only a definitive rejection signs the person out. signOut revokes the session on the server and clears it from the device.
If the person closes the sign-in sheet, signIn throws an error whose code is sign_in_cancelled. Treat it as a cancellation, not a failure, and check code rather than instanceof:
try {
await signIn('google')
} catch (error) {
if ((error as { code?: string }).code !== 'sign_in_cancelled') throw error
}
Records#
Records work as they do on the web. Wrap signed-in screens in RecordProvider and RecordScope, then use useQuery and useMutations. Import the schemas from the app's src/ folder so the client and the Worker share one definition:
import { RecordProvider, RecordScope, useMutations, useQuery } from 'deepspace/native'
import { schemas } from '../src/schemas'
function Home() {
return (
<RecordProvider>
<RecordScope roomId={`app:${APP_ID}`} schemas={schemas}>
<Items />
</RecordScope>
</RecordProvider>
)
}
RecordScope connects to the client's baseUrl and reconnects when the app returns to the foreground. Phones lose connectivity more often than browsers: when a write must not be lost, use the confirmed mutations (createConfirmed, putConfirmed, removeConfirmed). From deepspace 0.41 they survive a dropped connection. A write made while reconnecting waits and is sent, in order, once the room is back, and the room applies a resent write at most once. They reject when the Worker refuses the write, with WriteUnconfirmedError when the room leaves it unanswered on three fresh connections, with not_ready before the room's first connection, and (from 0.41.1) with WriteCancelledError when the write was still queued as the signed-in account changed or the screen holding it closed. Waiting offline never rejects, so an app needs no retry queue of its own. See data storage for queries, permissions, and write errors.
The user, presence, and messaging hooks are available too: useUser, useUsers, useUserLookup, usePresence, useMessages, useChannels, useReactions, useChannelMembers, and useReadReceipts.
Private data per account#
When each person's data is theirs alone, such as a task list, give every account its own room with accountStores from deepspace/worker. The owner keeps the app room; every other account gets <prefix>:<userId>; the Worker picks the room from the verified token, never from the name the client sends. The client asks for accountRoomId(userId):
// worker.ts
import { accountStores, registerAccountStoreRoute, registerAgentToolRoutes, RecordRoom } from 'deepspace/worker'
export const stores = accountStores({ prefix: 'tasks' })
export class AppRecordRoom extends RecordRoom<Env> {
constructor(state: DurableObjectState, env: Env) {
super(state, env, schemas, { ownerUserId: stores.ownerOf(env, state.id.name) ?? undefined })
}
}
registerAccountStoreRoute(app, stores) // before any route that opens a room by name
registerAgentToolRoutes(app, { buildTools, resolveAccess: stores.agentAccess(resolveAgentAuth) })
// mobile
<RecordScope roomId={accountRoomId(userId)} schemas={schemas}>
Make the collections admin-only: each room's account is its only admin, so nobody else can read or write it. This also closes the app room to everyone but the owner, so keep data every account shares in a separate room or serve it from the Worker.
Keyboard shortcuts and menus#
iPad apps run on Apple silicon Macs, and iPads take hardware keyboards. useKeyboardShortcuts registers shortcuts while the calling component is mounted. They work with nothing focused, list their titles in the iPad shortcut overlay (hold Command), and behave the same in the web build:
import { useKeyboardShortcuts } from 'deepspace/native'
useKeyboardShortcuts([
{ key: 'space', title: 'Show details', run: toggleDetails },
{ key: '1', run: () => answer(0) },
{ key: 'z', modifiers: ['command'], title: 'Undo', run: undo },
{ key: 'escape', whileTyping: true, run: close },
])
When two mounted components register the same key, the later one wins, so a sheet's Escape overrides the screen's. Pass { modal: true } for a dialog that should take every key. A shortcut runs while a text field has focus only with whileTyping: true. ContextMenu gives a view a long-press or right-click menu, isIOSAppOnMac tells the iPad build running on a Mac apart, and isPointerPrimary is true wherever the primary input is a pointer (pointerInput in 0.41.0, still available as a deprecated alias).
These use an Expo module that ships in the deepspace package and autolinks. Rebuild the app binary (npx expo run:ios, or a new EAS build) after upgrading to 0.41; until then, shortcuts do nothing.
The same app on the web#
deepspace/native has a browser build, so the Expo app can also be the app's web page without per-platform files. The same imports use the browser's cookie session, Alert becomes an in-page dialog that keeps the keyboard and focus until it closes, and openIntegrationConsent opens a window and resolves when it closes. Add react-dom, react-native-web and @expo/metro-runtime to mobile/, then export the app at vite build:
// vite.config.ts
import { fileURLToPath } from 'node:url'
import { deepspaceBuild, expoWeb } from 'deepspace/build'
export default defineConfig({
plugins: [
cloudflare(),
deepspaceBuild({ appDir }),
expoWeb({ mobileDir: fileURLToPath(new URL('./mobile', import.meta.url)) }),
],
})
For browser tests against that production build, servePreview from deepspace/testing builds the app, serves it with vite preview on fresh data (cloudflare(testState()) reads it), and can make a test account the owner.
Integrations and server actions#
integration calls the app's integration proxy exactly as on the web, and callAction posts to a server action:
import { callAction, integration } from 'deepspace/native'
const places = await integration.post('openweathermap/geocoding', { query: 'Brooklyn' })
const result = await callAction('archiveProject', { projectId })
if (!result.success) showError(result.error)
Per-user integrations such as Google answer with a consent URL until the person grants access (see Google OAuth). consentUrlOf reads that URL from a result, and openIntegrationConsent shows it in the system browser (a new window on the web) and resolves when it closes. The platform stores the grant, so retry the call afterwards:
import { consentUrlOf, integration, openIntegrationConsent } from 'deepspace/native'
let result = await integration.post('google/calendar-list-events', { maxResults: 10 })
const consentUrl = consentUrlOf(result)
if (consentUrl) {
await openIntegrationConsent(consentUrl)
result = await integration.post('google/calendar-list-events', { maxResults: 10 })
}
What the mobile entry includes#
deepspace/native exports the Expo client (createDeepSpaceExpoClient and its errors), DeepSpaceNativeProvider, useDeepSpace, useAuth, the record, user, presence, and messaging hooks above, WriteUnconfirmedError, WriteCancelledError, accountRoomId, useFileSource, integration, callAction, consentUrlOf, openIntegrationConsent, useKeyboardShortcuts, ContextMenu, isIOSAppOnMac, isPointerPrimary, and Alert. Import everything from deepspace/native so the app holds one copy of the client.
The web-only surfaces are not part of it: AuthOverlay, AuthGate, theming, file uploads with useR2Files, and the canvas, cron, job, and collaborative-editing hooks.
Show stored files#
On the web a private file renders from its URL because the browser sends the user's session. A native app has no session cookie for your app's origin, so a private file needs the user's token on every load. useFileSource turns a stored key (the key an upload returned) into the source React Native's <Image> and expo-video accept:
import { Image } from 'react-native'
import { useFileSource } from 'deepspace/native'
function Screenshot({ fileKey }: { fileKey: string }) {
const source = useFileSource(fileKey) // { uri, headers } or null
return source ? <Image source={source} style={{ width: '100%', aspectRatio: 16 / 10 }} /> : null
}
The default scope is 'self', the signed-in user's private files; the source is null until their token is ready and is rebuilt when the token refreshes. Pass { scope: 'app' } for public files, which need no token.
Build for devices#
Device and store builds go through EAS Build and need an iOS bundle identifier and Android package registered to your developer accounts. npx deepspace add mobile fills in placeholders based on the app name; replace them in mobile/app.config.ts before the first device build. No native project is committed: expo run:ios, expo run:android, and EAS generate it.
To put a signed build on TestFlight, run npx deepspace testflight <signed.ipa>. It finds the App Store Connect app from the IPA's bundle id, uploads the build, and waits until TestFlight offers it to the internal group. It reads the API key from the variables eas build --local already uses (EXPO_ASC_API_KEY_PATH, EXPO_ASC_KEY_ID, EXPO_ASC_ISSUER_ID) or from submit.production.ios in eas.json. See testflight.