This site counts visits with analytics cookies only if you accept. Read the consent

Skip to content

Framework GuidesReact Native & Expo

React Native & Expo

Courier in a React Native app: an absolute address, React Query hooks, streams through expo/fetch, channels, uploads from the device and cancellation, on Hermes.

10 min readUpdated direct mode

A React Native app calls its API as a page does in direct mode: the typed client, the React Query hooks, server-sent events, WebSocket channels, uploads with their progress, and cancellation. Each is checked on Hermes, in an Expo SDK 58 app, by the example in examples/expo.

In one command

bash
npx @noverax/create-courier

In an Expo app it adds your API at an address that suits the simulator, the emulator and a phone, React Query hooks for it, the mock Studio runs, and a Courier tab that shows it at work. See Create Courier.

Installation

bash
npm install @noverax/courier @noverax/courier-react
npx expo install @tanstack/react-query

An absolute address

An app has no page, so nothing resolves a path such as /api for it: the API's baseURL is an absolute URL. A path is refused before any request is sent, with a ConfigurationError whose code is URL_NOT_ABSOLUTE.

The computer that serves the API while you work on the app is localhost from the iOS simulator, 10.0.2.2 from the Android emulator, and its address on the network from a phone, which an EXPO_PUBLIC_ variable can carry:

src/address.ts
import { Platform } from "react-native"

export const API_URL =
  process.env.EXPO_PUBLIC_API_URL ??
  (Platform.OS === "android" ? "http://10.0.2.2:4000" : "http://localhost:4000")

The API and its client

The API is defined once, with that address, and both callers are built from it: the hooks for components, and plain calls for what a hook does not do.

src/api.ts
import { courier, defineApi, defineGroup } from "@noverax/courier/define"
import { API_URL } from "./address"

type User = { id: number; name: string }
type Stored = { name: string; size: number }
type Message = { text: string }

const { endpoint, stream, channel } = courier()

export const shop = defineApi({
  baseURL: API_URL,
  groups: {
    users: defineGroup({
      prefix: "users",
      endpoints: {
        list: endpoint.get("").response<User[]>(),
        search: endpoint.query("search").variables<{ name: string }>().response<User[]>().cancelPrevious(),
      },
    }),
    files: defineGroup({
      prefix: "files",
      endpoints: { upload: endpoint.post("").variables<FormData>().response<Stored>() },
    }),
    live: defineGroup({
      prefix: "live",
      endpoints: {
        ticks: stream.response<{ n: number }>().get("ticks"),
        chat: channel.send<Message>().response<Message>().connect("chat"),
      },
    }),
  },
})
src/client.ts
import { createCaller } from "@noverax/courier/client"
import { createQueryCaller } from "@noverax/courier-react"
import { QueryClient } from "@tanstack/react-query"
import { shop } from "./api"

export const q = createQueryCaller(shop)
export const client = createCaller(shop)
export const queryClient = new QueryClient()

Wrap the app in QueryClientProvider with that client, and a component reads as it would on the web:

src/users.tsx
import { Text } from "react-native"
import { q } from "./client"

export function Users() {
  const users = q.users.useQuery("list")
  const found = q.users.useQuery("search", { variables: { name: "a" } })
  return <Text>{users.data?.length} users, {found.data?.length} found</Text>
}

The user's session

An API that keeps the user's session in cookies says so where it is defined, as it does for a page — see User Sessions. The platform keeps the cookies the API sets and sends them with the calls to its host, as a browser does; a call asks for them with credentials: "include".

What a page reads from document.cookie — the double-submit token a write repeats, a bearer token the API did not set HttpOnly — an app cannot read: React Native keeps its cookies where no script reaches them. It hands a script the Set-Cookie headers of each answer instead, so Courier keeps those cookies from the answers its calls receive, for the host, domain and path they were set for, until they run out or the API deletes them, and repeats them as a page does. A Domain of one label, such as com, would reach every other API of the app and is not taken; a browser refuses every public suffix by its list, co.uk too, which an app does not ship.

A token is kept for as long as the app runs. When the app starts again, the platform still sends the cookie it kept, but no write could repeat it until an answer set it again — so name where the API hands it out, and the first write that finds none asks there itself, with the user's session:

src/account.ts
import { createCaller } from "@noverax/courier/client"
import { courier, defineApi } from "@noverax/courier/define"
import { API_URL } from "./address"

const { endpoint } = courier()

export const account = createCaller(
  defineApi({
    name: "account",
    baseURL: API_URL,
    session: {
      cookies: ["laravel_session"],
      csrf: { cookie: "XSRF-TOKEN", header: "X-XSRF-TOKEN", from: "/sanctum/csrf-cookie" },
    },
    endpoints: {
      signIn: endpoint.post("login").variables<{ email: string; password: string }>(),
      rename: endpoint.post("user/name").variables<{ name: string }>(),
    },
  }),
)

from is a path under the API's address, such as "csrf/" for a Django view decorated with ensure_csrf_cookie, or one from the root of its origin, as Laravel Sanctum's is. Only the answers to Courier's own calls hand it the cookies: an answer to a plain fetch does not. See When there is no token yet.

Every call to the host carries its cookies

React Native sends the cookies it keeps for a host with every call to that host, whether the API describes a session or not; a browser sends them to another origin only when the call asks it to.

Redirects

React Native follows every redirect itself, wherever it leads and whatever a call's redirect says: its XMLHttpRequest does, and so does React Native's own fetch, which sends through it. On Android a call goes on to another host with every header it carries but Authorization; on iOS with none but the cookies the platform keeps for that host. expo/fetch follows one only as redirect says.

A call that must take its credentials nowhere but its API's origin says so with withinOrigin: true, as a server's call that carries the user's session always does. Courier then follows a redirect only while it stays on that origin, and answers with one to anywhere else as it came: an HTTPError with the redirect's status. Without it a call follows redirects as the platform does, the user's session's too: the platform keeps its cookies to the host that set them, as a browser does, but on Android a token Courier repeats as a header goes on with the call.

src/users-within-origin.ts
import { client } from "./client"

export function listUsers() {
  return client.users.with({ withinOrigin: true }).list()
}

Such a call takes expo/fetch and never goes through XMLHttpRequest, so its upload reports no progress, nor its download unless it is read as it comes, with stream: true. With React Native's own fetch, or with a form naming a file on the device, which only XMLHttpRequest sends, it is refused before it is sent, with a ConfigurationError WITHIN_ORIGIN_UNAVAILABLE. Through a fetch of the app's own that sends with React Native's, it is refused once that fetch hands over an answer from another origin: the redirect was followed before the answer came, so the call's credentials may have gone there.

Streams and channels

useSubscription reads server-sent events as they arrive, which takes a fetch that hands over a response's body as it comes. React Native's own fetch hands it over only once all of it has arrived; Expo replaces it with expo/fetch, which streams. Expo SDK 58 does so for every app unless EXPO_PUBLIC_USE_RN_FETCH is set. With React Native's own, a stream is refused as it is opened, with a ConfigurationError RESPONSE_STREAM_UNAVAILABLE that useSubscription reports through error, rather than reconnected again and again for events that would never come. Through a fetch of the app's own that sends with React Native's, it is refused once that fetch hands an answer over — a refusal, or a stream the server ended; a stream that stays open it never hands over, so such a fetch sends its streams with expo/fetch.

A channel needs nothing more: React Native has WebSocket. Its socket sends the API's own address as its Origin, which a Courier server admits as its own, with no entry in allowedOrigins — behind a proxy, once the proxy passes on the scheme and host the app used, as Behind a Reverse Proxy shows. Where no WebSocket gets through, the channel goes on over HTTP to the socket's path, as a page's does — on a stream under expo/fetch, on polls under React Native's own fetch — see When no WebSocket gets through. When the app is back in the foreground, resumeRealtime("visible") from @noverax/courier/realtime has its channels and streams act on it as a page's act on being shown again — see Staying connected.

src/live.tsx
import { Button, Text } from "react-native"
import { q } from "./client"

export function Live() {
  const ticks = q.live.useSubscription("ticks")
  const chat = q.live.useChannel("chat")
  return (
    <>
      <Text>tick {ticks.data?.n}</Text>
      <Button title="Say hello" onPress={() => chat.send({ text: "hello" })} />
    </>
  )
}

A call that reads its answer as it comes, with stream: true, takes such a fetch too. With React Native's own it is refused before it is sent, with a ConfigurationError RESPONSE_STREAM_UNAVAILABLE, rather than left waiting for an answer that may never end; through a fetch of the app's own that sends with React Native's, once it is answered.

Uploads from the device

React Native's FormData takes a file on the device by its address, name and type. Courier sends a form holding one through XMLHttpRequest, which reads the file from where it is — expo/fetch refuses such a form — and reports the upload's progress when you ask for it:

src/upload.ts
import { client } from "./client"

export async function upload(uri: string, onProgress: (share: number) => void) {
  const form = new FormData()
  /* The DOM's FormData type has no file given by its address. */
  form.append("photo", { uri, name: "photo.jpg", type: "image/jpeg" } as unknown as Blob)
  return client.files.with({ onUploadProgress: (p) => onProgress(p.percent) }).upload(form)
}

Its answer is read as React Native's own fetch reads one, from the Blob XMLHttpRequest hands over: the text as UTF-8, and with responseType: "blob" that Blob itself. A form whose files the app holds as bytes — a Blob — goes with the app's fetch. A stream an upload sends is read whole first, as expo/fetch reads one: neither React Native's fetch nor XMLHttpRequest can send a stream. A call cancelled, or out of time, while its stream is read stops reading it.

An API that sends its calls with a fetch of its own sends these through it too, and no upload through it reports its progress. That fetch must then read a file on the device itself: React Native's own fetch does, expo/fetch does not. A token goes with the API's headers or authMiddleware, which XMLHttpRequest sends as well.

A call that reads its answer as it comes, with stream: true, goes with the app's fetch instead, since XMLHttpRequest hands an answer over only once all of it has arrived. Its upload then reports no progress, and under expo/fetch its form holds its files as bytes, a Blob: that fetch refuses one naming a file on the device.

Download progress

A call that reports its download goes through XMLHttpRequest, which reports the answer as it arrives, against the length the answer declares. React Native's own fetch hands an answer over only once all of it has arrived, and the Response an app has cannot be made of the stream expo/fetch hands over, which is how Courier counts a download elsewhere. The answer is read as any other is:

src/users-progress.ts
import { client } from "./client"

export function listUsers(onProgress: (share: number) => void) {
  return client.users.with({ onDownloadProgress: (p) => onProgress(p.percent) }).list()
}

A call that reads its answer as it comes, with stream: true, goes with expo/fetch, and its stream is counted as it is read.

An API with a fetch of its own sends a call that reports its download through that fetch, as every call of the API: the download is counted only as the call reads a stream that fetch hands over.

Cancellation and timeouts

A call is cancelled through its signal, and rejects with an AbortError:

ts
const controller = new AbortController()
const pending = client.users.with({ signal: controller.signal }).list()
controller.abort()
await pending // rejects with an AbortError

React Native's own fetch rejects a cancelled request with an AbortError of its own, and expo/fetch reports one as a fetch that failed. Either way the call rejects with Courier's AbortError, never with a network failure, even where the AbortController keeps no reason, as React Native's did up to 0.86 — Expo SDK 57's; where it keeps one, as 0.88's does, that reason is the error's cause. A call whose timeout runs out rejects with a TimeoutError, though React Native's fetch reports it as an abort.

Identical reads in flight together share one request in an app as everywhere, and cancelPrevious works as it does in a browser, since an app serves one user: a newer search cancels the one before it. See Deduplication & Abort.

Without Expo

React Native without Expo lacks more of the web platform: crypto.randomUUID, structuredClone, a global DOMException and web streams, and its URL reads only part of an address; up to 0.86 it lacks AbortSignal.any and AbortSignal.timeout too. Courier does without each where it uses it, so calls, uploads, cancellation, timeouts, the cache middleware and channels work as they are: over WebSocket and, where no WebSocket gets through, on polls over HTTP. A stream of server-sent events and a call that reads its answer as it comes alone need more: a fetch that streams, installed as the global one before the first such call or given as the API's fetch — with React Native's own, each is refused with RESPONSE_STREAM_UNAVAILABLE — and for the events a TextDecoder, which React Native 0.88's Hermes has.

Working against a mock

Studio runs the mock the app calls while you work, from the project's courier.mocks.ts, and shows each request the app makes. The example's mock serves the shop on port 7020:

bash
npm run server
npx expo start

The first starts Studio with its mock, the second the app. See Mock Servers for what a mock answers and how.