React Native apps
View as MarkdownA native app is one more entry point to the same hub. It talks only to your backend (the hub), signs in with a bearer token you issue, and drives the user’s own computer exactly like your website does. The app never holds a machine token and never talks to the computer directly.
@uncage/client and @uncage/react (the headless hooks) run in React Native without changes. They import nothing from react-native or expo-*; everything platform-specific is an adapter your app passes in. There is no React Native UI kit: examples/connected-expo shows how to build the screens with the hooks, to copy rather than install.
1. Hub side
Section titled “1. Hub side”Your hub needs two things for apps: a getUser that accepts your app’s token (authenticate apps), and, optionally, push (push notifications). Native requests carry no Origin header, so the hub’s cross-site guard lets them through; a browser page from another site is still refused.
2. The client
Section titled “2. The client”Install the packages and create the client with a streaming fetch and your token:
import { createUncageClient } from '@uncage/client';import { fetch as streamFetch } from 'expo/fetch';
export const client = createUncageClient({ baseUrl: 'https://your.site/api/uncage', fetch: streamFetch, // Called for every request and every stream (re)connect; may be async (token refresh). headers: async () => ({ authorization: `Bearer ${await getToken()}` }),});- Streaming. React Native’s built-in
fetchcannot stream a response body, and the client reads events fromresponse.body.getReader(). Expo’sexpo/fetchstreams. In bare React Native use anyfetchpolyfill that exposesbody.getReader(). WhereTextDecoderis missing (older Hermes) the client uses a small built-in UTF-8 decoder. - Uploads.
uploadAttachmentaccepts a browserFileor an{ uri, name, type }object fromexpo-image-picker. For the second form the client reads the file with the globalfetch(uri)then sends it through yourfetch. In Expo SDK 58 and later the globalfetchisexpo/fetch(React Native’s ownfetchonly withEXPO_PUBLIC_USE_RN_FETCH=1). It readsfile://URIs but notcontent://:expo-image-pickeralready hands overfile://copies, and anycontent://URI must be copied to a cache file first.examples/connected-expokeeps event streams onexpo/fetchand sends other requests through the global one.useAttachments().add()accepts the same{ uri, name, type, size? }file references (theAttachmentFiletype) as well as namedBlobs. - Images.
client.attachmentUrl(id)needs the auth header, so render with<Image source={{ uri, headers }} />. - Async headers. If
headers()throws (a failed token refresh) requests fail withunauthorizedanddetails.reason: 'headers'; the stream reports it throughonErrorand retries.
3. Hooks
Section titled “3. Hooks”Wrap the app in UncageProvider and use the hooks as on the web (useMachines, useSession, useRuns, useApprovals, … ). Three things are specific to apps:
import { usePersistSession, useReconnect, type PersistSessionStorage } from '@uncage/react';import * as SecureStore from 'expo-secure-store';import { useEffect } from 'react';import { AppState } from 'react-native';
const storage: PersistSessionStorage = { get: () => SecureStore.getItemAsync('uncage.session'), set: (id) => (id === undefined ? SecureStore.deleteItemAsync('uncage.session') : SecureStore.setItemAsync('uncage.session', id)),};
export function useAppLifecycle() { usePersistSession(storage); // reopen the last conversation after a restart const reconnect = useReconnect(); useEffect(() => { const sub = AppState.addEventListener('change', (s) => s === 'active' && reconnect()); return () => sub.remove(); }, [reconnect]);}usePersistSession(storage)takes an adapter{ get, set }(sync or async: AsyncStorage, SecureStore, MMKV). With the default'url'or with'localStorage'and nowindow/localStorageit does nothing and never throws.useReconnect()returnsclient.reconnect(): it restarts every open event stream at once from its last sequence, so after the app was in the background for minutes nothing is lost and nothing repeats. Call it whenAppStatebecomesactive. A stream that is healthy (bytes arrived in the last 20 seconds) is kept;reconnect({ force: true })restarts it anyway.useDeviceApproval(code, { source })drives the approve screen below.
4. Approving a computer from the phone
Section titled “4. Approving a computer from the phone”uncage setup prints the approval link as a terminal QR code (--no-qr turns it off; it is skipped when the output is not a terminal). If you map the hub’s verification path (/device by default) to your app with Android App Links or iOS universal links, scanning the code opens your approval screen; otherwise the phone opens your mobile web approval page.
import { useDeviceApproval, type DeviceCodeSource } from '@uncage/react';
export function ApproveScreen({ code, source }: { code: string; source: DeviceCodeSource }) { // source: 'link' (a verified app link: untrusted on its own) or 'typed' (the user typed the whole code). const { lookup, state, error, confirmation, approve, deny } = useDeviceApproval(code, { source }); // state: 'loading' | 'idle' | 'approving' | 'denying' | 'approved' | 'denied' // | 'not_found' | 'expired' | 'error' // lookup: { name?, os?, expiresAt, requestedAt, requestIp, repairsMachine } | null. // confirmation: { required, typed, matched, setTyped }: with 'link', approve() waits until // the user typed the code's last 4 characters (setTyped) and matched is true. // error: { code, message }, e.g. 'rate_limited' (10 wrong codes in 10 minutes). return null; // render the warning, lookup, a last-4 input, error, and approve() / deny() buttons}Phishing guard. Anyone can run uncage setup against your site on their own computer and send a user the link, and any app or web page can open your custom URL scheme. So:
- Never pre-fill a code from your custom scheme (
yourapp://device?code=…): open the screen where the user types the code (source: 'typed'). - A code from a verified https App Link / universal link for your own site (the OS checked your
assetlinks.json/apple-app-site-association) may be pre-filled, assource: 'link'(the default):approve()does nothing until the user typed the code’s last 4 characters (confirmation.setTyped,confirmation.matched). Hide those 4 characters on screen. - Either way show the warning “Only approve if you just ran
uncage setupon a computer in front of you. Never approve a code someone sent you.”, the request time (lookup.requestedAt, as relative time) and IP (lookup.requestIp).deny()never needs the extra step.
examples/connected-expo does exactly this (app/+native-intent.tsx, lib/links.ts, app/device.tsx).
state is 'error' when the lookup itself failed (for example rate_limited); call retry() to run the lookup again; a failed decision returns to 'idle' with error set so the user can retry. approve() and deny() act only from 'idle'. Under the hood these call GET /device/lookup and POST /device/decision; client.lookupDevice(code) and client.decideDevice(code, approve) are the same without React.
- Android App Links: serve
/.well-known/assetlinks.json(package name and signing-certificate fingerprint) from your site.examples/connected-demobuilds it fromANDROID_PACKAGEandANDROID_SHA256. Built and unit-tested; awaiting device confirmation. - iOS universal links: serve
/.well-known/apple-app-site-association(Team ID and bundle id:APPLE_TEAM_ID,IOS_BUNDLE_IDin the demo). Needs a paid Apple Developer account; implemented and configurable, not verified on a device. On iOS the QR code falls back to the mobile web approval page.
Without a paid account
Section titled “Without a paid account”Everything except iOS links and iOS push works with free tools: Expo Go for chat, computers, approvals, pickers and photos; a free Expo account with EAS for an Android development build (push, App Links); a free Firebase project for Android push. The example’s README has the steps.
Authenticate apps · Push notifications · Custom UI · HTTP API