> ## Documentation Index
> Fetch the complete documentation index at: https://docs.fish.audio/llms.txt
> Use this file to discover all available pages before exploring further.

# React Native SDK

> Add voice calls with your agent to an iOS or Android app with @fishaudio/agent-react-native, in Expo or bare React Native

`@fishaudio/agent-react-native` adds voice calls with your agent to a React Native app. The call runs on the same code as the [Web SDK](https://docs.fish.audio/agents/deploy/web-sdk.md), so connection handling, transcripts, client tools, and end reasons behave the same. The hooks are the [React SDK](https://docs.fish.audio/agents/deploy/react-sdk.md)'s. On top of that, the package handles what phones need:

* The microphone permission on Android
* The platform audio session and routing (loudspeaker, earpiece, headsets)
* Background calls: an Android foreground service and iOS background audio
* An Expo config plugin for the native settings

It works in Expo apps and in bare React Native apps. Expo is not required.

> [card] [React SDK](https://docs.fish.audio/agents/deploy/react-sdk.md)
>
> The hook API this package builds on.

> [card] [Authenticated sessions](https://docs.fish.audio/agents/deploy/authenticated-sessions.md)
>
> Create session tokens on your backend.

> [card] [Web SDK reference](https://docs.fish.audio/agents/deploy/web-sdk.md)
>
> Events, client tools, and error codes.

## Requirements

* **A native build.** WebRTC is a native module. In Expo, build with `npx expo run:ios` / `run:android` or EAS Build. Expo Go cannot run it (`expo-dev-client` is optional). Bare React Native apps build as usual; see [Bare React Native](#bare-react-native).
* **A physical device** for anything involving the microphone.
* **Your own backend** to create session tokens, or a [public agent](#public-agent). Never ship an API key inside an app.
* **Tested with** Expo SDK 58 and bare React Native 0.88, `@livekit/react-native` 3.1, `@livekit/react-native-webrtc` 150.1, and `livekit-client` 2.20 to 2.23, on iOS 26 and Android 17. Other versions may work but are untested.

## Install (Expo)

```bash theme={null}
npx expo install @fishaudio/agent-react-native @livekit/react-native @livekit/react-native-webrtc \
  @livekit/react-native-expo-plugin @config-plugins/react-native-webrtc livekit-client
```

`npx expo install` adds the three config plugins to `app.json` for you. If you installed with npm or yarn instead, add them yourself:

```json app.json theme={null}
{
  "expo": {
    "plugins": [
      "@livekit/react-native-expo-plugin",
      "@config-plugins/react-native-webrtc",
      [
        "@fishaudio/agent-react-native",
        { "microphonePermission": "Talk to our assistant by voice." }
      ]
    ]
  }
}
```

Then build the native app with `npx expo run:ios --device` or `npx expo run:android --device`. Rebuild whenever you add a package with native code. After changing a plugin or its options, run `npx expo prebuild` first: once the `ios` and `android` folders exist, `run:ios` and `run:android` do not apply plugin changes. A JavaScript reload picks up neither.

| Plugin option | Default | Description |
| - | - | - |
| `microphonePermission` | `"Allow $(PRODUCT_NAME) to use the microphone for voice calls."` | iOS microphone prompt text. `false` leaves `NSMicrophoneUsageDescription` alone |
| `backgroundAudio` | `true` | Adds the iOS `audio` background mode, so calls continue in the background and with the screen locked |

Android needs no configuration: the package's manifest adds the microphone, audio, and foreground-service permissions and the service itself when the app is built.

## Bare React Native

Without Expo, install the packages without the config plugins and set the native options yourself:

```bash theme={null}
npm install @fishaudio/agent-react-native @livekit/react-native @livekit/react-native-webrtc livekit-client
```

**1. Set up LiveKit**

Follow the [LiveKit React Native installation](https://github.com/livekit/client-sdk-react-native#installation) for its native setup. It replaces the two LiveKit and WebRTC config plugins. In short:

* Android `MainApplication.kt`: call `LiveKitReactNative.setup(this, AudioType.CommunicationAudioType())` in `onCreate`.
* iOS `AppDelegate.swift`: `import livekit_react_native`, then call `LivekitReactNative.setup()` in `didFinishLaunchingWithOptions`.
* iOS `Podfile`: LiveKit's WebRTC pod comes from LiveKit's own spec repo. Add both sources at the top, then run `cd ios && pod install --repo-update`:

  ```ruby Podfile theme={null}
  source 'https://github.com/livekit/podspecs.git'
  source 'https://cdn.cocoapods.org/'
  ```

**2. Configure iOS**

Add the microphone text, and the `audio` background mode so calls continue in the background:

```xml Info.plist theme={null}
<key>NSMicrophoneUsageDescription</key>
<string>Talk to our assistant by voice.</string>
<key>UIBackgroundModes</key>
<array>
  <string>audio</string>
</array>
```

**3. Build**

Android needs nothing extra: autolinking registers the package's module, and its manifest brings the permissions and the foreground service. Build with `npx react-native run-ios` or `run-android`.

## Set up the entry file

`setupFishAgent()` installs the WebRTC globals the SDK runs on. Call it before your app's modules load: put it in a file of its own and import that file first in your entry file. A call in the entry file's body is not enough, since every import in a file runs before its body. `startSession` also installs the globals if they are missing, so a forgotten call does not break calls, but code that touches WebRTC earlier would fail.

```ts setupFishAgent.ts theme={null}
import { setupFishAgent } from "@fishaudio/agent-react-native";
setupFishAgent();
```

```ts index.ts (expo-router) theme={null}
import "./setupFishAgent";
import "expo-router/entry";
```

```ts index.ts (Expo, no router) theme={null}
import "./setupFishAgent";
import { registerRootComponent } from "expo";
import App from "./App";

registerRootComponent(App);
```

```ts index.js (bare React Native) theme={null}
import "./setupFishAgent";
import { AppRegistry } from "react-native";
import App from "./App";
import { name as appName } from "./app.json";

AppRegistry.registerComponent(appName, () => App);
```

With expo-router (the default `create-expo-app` template), also point `main` in `package.json` at the new file: `"main": "index.ts"`.

## Quick start

```tsx SupportCall.tsx theme={null}
import {
  useAgentMessages,
  useConversation,
} from "@fishaudio/agent-react-native";
import { useRef } from "react";
import { Button, FlatList, Text, View } from "react-native";

export default function SupportCall() {
  const conversation = useConversation(
    { clientTools: { show_order: async ({ orderId }) => ({ shown: true }) } },
    { callNotification: { title: "Talking to support" } }
  );
  const messages = useAgentMessages(conversation.session);
  const attempt = useRef(0);

  const start = async () => {
    const current = ++attempt.current;
    const sessionToken = await fetch("https://api.example.com/agent-session", {
      method: "POST",
    }).then(r => r.json());
    // The user hung up while the token was on its way.
    if (current !== attempt.current) return;
    await conversation.startSession({ sessionToken });
  };

  const hangUp = () => {
    attempt.current++;
    void conversation.endSession();
  };

  return (
    <View style={{ flex: 1, padding: 16, gap: 12 }}>
      <Text>
        {conversation.status} · {conversation.mode}
      </Text>
      <Button title="Call" onPress={() => void start()} />
      <Button title="Hang up" onPress={hangUp} />
      <FlatList
        data={messages}
        keyExtractor={m => m.key}
        renderItem={({ item }) => (
          <Text>
            {item.role}: {item.text}
          </Text>
        )}
      />
    </View>
  );
}
```

`startSession` asks for the microphone on Android the first time (iOS asks on its own when capture starts), so call it from a button press.

## Start a session

An app starts a call in one of two ways, the same two the browser SDKs offer.

### From your backend (recommended)

When the user starts a call, the app asks your backend for a session token. The backend calls `POST /v1/agent/sessions` with your API key and returns the response unchanged, and the app passes it to `startSession({ sessionToken })`. The endpoint is the same one web apps use; see [Authenticated sessions](https://docs.fish.audio/agents/deploy/authenticated-sessions.md) for backend examples.

Two things differ from the browser:

* **`localhost` is the phone, not your computer.** During development, use your computer's LAN address, or on Android forward the port with `adb reverse tcp:3001 tcp:3001`.
* **iOS blocks plain `http://`** outside development builds. Serve the token endpoint over HTTPS.

### Public agent

An agent with [public access](https://docs.fish.audio/agents/deploy/public-agents.md) turned on takes sessions with just its id, with no API key and no backend:

```ts theme={null}
await conversation.startSession({ agentId: "YOUR_AGENT_ID" });
```

If the agent has **Restrict origins** on, the platform checks the request's `Origin` header against the agent's allowed origins. Browsers send their page's origin themselves; an app sends none, so pass one that is on the list:

```ts theme={null}
await conversation.startSession({
  agentId: "YOUR_AGENT_ID",
  origin: "https://www.example.com",
});
```

> [!WARNING]
>
> The `origin` option is experimental and may change in a minor release: a
> dedicated way for apps to identify themselves may replace it.

Know what a public agent means before shipping one in an app:

* **Anyone with the agent id can start sessions, billed to you.** An app can be unpacked, and any client can send any `Origin`, so restricting origins does not make an agent private. [Rate limits](https://docs.fish.audio/agents/deploy/public-agents.md#rate-limiting) are the backstop, and public sessions accept only a few [overrides](https://docs.fish.audio/agents/deploy/public-agents.md#treat-public-input-as-untrusted).
* **Prefer your backend for production apps**, especially with signed-in users: it decides who gets a token and can attribute sessions to your users.

## `useConversation(defaults?, options?)`

The [React SDK hook](https://docs.fish.audio/agents/deploy/react-sdk.md) with the same arguments, return values, and lifecycle, plus:

| Field | Type | Description |
| - | - | - |
| `startSession` | `(overrides?) => Promise<string>` | Before connecting, also requests the Android microphone permission (rejects with `mic_permission_denied` on a no), sets up the audio session and route, and on Android starts the call's foreground service |
| `endSession` | `() => Promise<void>` | Also releases the audio session and stops the foreground service. Both are also released when the agent hangs up or the connection drops |
| `audioOutput` | `"auto" \| "speaker" \| "earpiece"` | The route you asked for, not the device currently playing |
| `setAudioOutput` | `(route) => Promise<void>` | Change the route, before or during a call |

Audio routes:

* `auto` (default): a connected Bluetooth or wired headset, otherwise the loudspeaker.
* `speaker`: always the loudspeaker, even with a headset connected.
* `earpiece`: the phone's receiver, for holding it to the ear.

The second argument takes mobile options:

| Option | Default | Description |
| - | - | - |
| `audioOutput` | `"auto"` | Initial route |
| `callNotification` | `{ title: "Call in progress" }` | Android: the ongoing notification shown during a call, `{ title, text }`. `false` turns off the foreground service, and the microphone is then silenced while the app is in the background |

Everything else (`status`, `mode`, `micMuted` / `setMicMuted`, `sendUserMessage`, `interrupt`, `session`, client tools, callbacks, and errors) works as described in the [React SDK](https://docs.fish.audio/agents/deploy/react-sdk.md) and [Web SDK](https://docs.fish.audio/agents/deploy/web-sdk.md#events) pages. `useAgentMessages` and `AgentSessionProvider` are re-exported from the React SDK and work the same way.

Not available on React Native:

* The browser-only members of the React hook (`startAudio`, `setOutputVolume`, `setInputDevice`, `setOutputDevice`).
* `useAudioLevels` and `AgentAudioVisualizer`.
* Starting calls with `AgentSession` directly. It is exported as a type only, for `conversation.session`. Start calls through `useConversation`, which also handles the permission, audio session, and call service.

## Background calls

* **iOS:** with the `audio` background mode (on by default in the plugin), a call continues when the app goes to the background or the screen locks. The user can keep talking and hear the agent.
* **Android:** during a call, the SDK runs a microphone foreground service with an ongoing notification. Android 14 and later silence an app's microphone as soon as it leaves the foreground unless such a service runs.
* **Google Play:** the package adds a microphone-type foreground service and its permissions to your app. Declare its use in Play Console before publishing, as Google Play requires.
* **Android 13+ notifications:** the call notification only shows if the app holds `POST_NOTIFICATIONS`, which Android 13 and later grant at runtime. The SDK declares it but does not ask for it, so the prompt stays under your control. Without it, the service still runs and background capture still works; only the notification is hidden. To show it, ask before the first call:

  ```ts theme={null}
  import { PermissionsAndroid, Platform } from "react-native";

  if (Platform.OS === "android" && Platform.Version >= 33) {
    await PermissionsAndroid.request(
      PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS
    );
  }
  ```

## Troubleshooting

| Symptom | Cause and fix |
| - | - |
| Errors about a missing native module in Expo Go | Expo Go cannot load WebRTC. Build the app with `npx expo run:ios` or `run:android` |
| Warning `Native module missing: background calls will lose the microphone` | The app was not rebuilt after installing the package. Rebuild the native app |
| `startSession` rejects with `connection_failed` | Check that the token came from `POST /v1/agent/sessions`, that it was used right away (tokens are short-lived), and that the device has network. If you call LiveKit or WebRTC APIs before the first call, call `setupFishAgent()` in the entry file |
| A plugin change has no effect (missing microphone text, no background audio) | Native settings only change through prebuild. Run `npx expo prebuild`, then `run:ios` / `run:android` again. In bare React Native, check `Info.plist` and rebuild |
| iOS `pod install` cannot find `LiveKitWebRTC` | The LiveKit pod sources are missing from the top of the `Podfile`; see [Bare React Native](#bare-react-native) |
| A public agent fails with `origin_forbidden` | The agent restricts origins. Pass `origin` to `startSession`, matching an allowed origin exactly (scheme, host, and port) |
| `fetch` to your token endpoint fails on the phone | `localhost` points at the phone. Use your computer's LAN address or `adb reverse`, and HTTPS on iOS |
| Android: the agent stops hearing the user while the app is in the background | `callNotification` is `false`, or the app was not rebuilt after installing the package, so the foreground service is missing |
| A prompt about local networks or nearby devices at first launch | Debug builds look for the development server on the local network. It does not come from the call |
| On iPhones sold in mainland China, an "Allow to use wireless data" prompt at first network use | The system asks this for every new app. Choose WLAN & Cellular |
| `ping timeout triggered` or `not found in senderGetStats()` warnings after hanging up | Harmless messages from LiveKit's teardown. To quiet them: `import { setLogLevel } from "livekit-client"; setLogLevel("warn");` |
| Odd failures after installing in a monorepo | Make sure only one copy of `@livekit/react-native` and `livekit-client` is installed (`npm ls @livekit/react-native livekit-client`) |

## Going further

> [card] [Client tools](https://docs.fish.audio/agents/build/client-tools.md)
>
> Let the agent call functions in your app.

> [card] [Authenticated sessions](https://docs.fish.audio/agents/deploy/authenticated-sessions.md)
>
> Create session tokens server-side.

> [card] [Public agents](https://docs.fish.audio/agents/deploy/public-agents.md)
>
> Public access, origin restriction, and rate limits.

> [card] [Dynamic variables](https://docs.fish.audio/agents/build/dynamic-variables.md)
>
> Personalize each session at start time.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.