# React Native reference

> Every public type in the FacePing React Native package: setup, enrolment, verification, the camera component and results.

Source: https://docs.faceping.ai/sdk/react-native/

Package: [`@faceping/react-native`](https://www.npmjs.com/package/@faceping/react-native) (npm, preview, under the `preview` tag). Starter app: [faceping/react-native-starter](https://github.com/faceping/react-native-starter). Android 7 (API 24) or later, on 64-bit phones (`arm64-v8a`) and `x86_64` emulators. iOS 15.1 or later (16.4 or later in an Expo SDK 57 app, Expo's own minimum); Xcode 26 or later. Node 20.19.4 or later.

The package is a thin bridge over the native [Android](https://docs.faceping.ai/sdk/android/) and [iOS](https://docs.faceping.ai/sdk/ios/) SDKs, built with [Expo modules](https://docs.expo.dev/modules/overview/): it works in any Expo app with a development build (not Expo Go), and in bare React Native apps with Expo modules installed. New and old architecture. Tested with Expo SDK 57 and React Native 0.86.

## Install

### Expo

```bash
npx expo install @faceping/react-native@preview
```

`npx expo install` adds the config plugin to `app.json`. Give it options as below, then rebuild (`npx expo prebuild`, `npx expo run:ios`, `npx expo run:android`, or EAS Build):

```json title="app.json"
{
  "expo": {
    "plugins": [
      ["@faceping/react-native", { "cameraPermission": "We use the front camera to check it's you." }]
    ]
  }
}
```

| Plugin option | Default | Notes |
|---|---|---|
| `cameraPermission` | A generic sentence | The iOS camera prompt, set as `NSCameraUsageDescription`. Without it, iOS stops the app when the camera starts. |
| `androidAbis` | `true` | Builds Android for `arm64-v8a` and `x86_64` only, the ABIs FacePing runs on. `false` keeps your own list. |
| `androidBackupRules` | `true` | Adds Android backup rules that leave FacePing's data out of backups and phone-to-phone transfers (see [Backups](#android-backup)). `false` leaves backup rules to you. |

### Bare React Native

```bash
npx install-expo-modules@latest     # once, if your app doesn't use Expo modules yet
npm install @faceping/react-native@preview
cd ios && pod install
```

Then do by hand what the plugin does:

- **iOS:** add `NSCameraUsageDescription` to `Info.plist` (Xcode: the target's **Info** tab, **Privacy - Camera Usage Description**), and make sure the deployment target is 15.1 or later.
- **Android:** in `android/gradle.properties`, set `reactNativeArchitectures=arm64-v8a,x86_64`.

### How the native SDKs get into your app

- **Android:** the module depends on `ai.faceping:faceping-android` from Maven Central. Gradle fetches it like any other dependency, with the `CAMERA` and `INTERNET` permissions.
- **iOS:** `pod install` downloads `FacePing.xcframework.zip` once from the [faceping-ios release](https://github.com/faceping/faceping-ios/releases), checks its SHA-256 against the checksum pinned in the package, and vendors it. Offline or behind a proxy, set `FACEPING_IOS_ZIP=/path/to/FacePing.xcframework.zip` (checked the same way) or `FACEPING_IOS_URL` to a mirror before `pod install`. The simulator has no front camera: test the live check on an iPhone.

## Setup

```tsx
import { FacePing } from '@faceping/react-native';

// Once, early. Resolves at once and loads the face models in the background.
await FacePing.init({ sandboxKey: 'fp_test_…' });   // sandbox: faces enrolled on the device
// await FacePing.init({ deviceToken: 'fpd_…' });   // production or your practice list: faces synced from that list

// Optional: activates the sandbox key now (or downloads a device's list), so a key problem shows up before the first
// person arrives. Without it, the first enrol or verify activates the key.
await FacePing.sync();
```

`FacePing` is a single object you can call from anywhere in the app. Calling `init` again with the same options is fine (for example after a fast refresh); with different options it throws (call `close()` first). It resolves to `{ isSandbox, nativeSdkVersion }`.

A key in the wrong format throws a `setup` error from `init`. A revoked key, or a first run with no connection, shows up on the first call that needs the key. You don't have to sync first; calling `sync()` at start-up just finds those problems sooner.

### Options

| Option | Type | Default | Notes |
|---|---|---|---|
| `sandboxKey` | `string` | | A `fp_test_` key from [**Developers → Sandbox keys**](https://app.faceping.ai/developers). |
| `deviceToken` | `string` | | Production, or your sandbox's practice list. A `fpd_` device token for one check-in list (from `POST /v1/lists/{listId}/devices`, or the list's Devices tab). Set this or `sandboxKey`, not both. |
| `region` | `'eu'` | `'eu'` | Your account's region, which sets the API address. Today the only value is EU (`https://api-eu.faceping.ai/`). |
| `apiBaseUrl` | `string` | | Overrides the region's address. UK and US regions are available on request: we give you the address to put here. |
| `passiveLiveness` | `boolean` | `true` | Passive liveness on every check. Turn it off only if your app runs its own liveness check first. |
| `autoSyncInterval` | `number \| null` | `300` | With a device token (production, or a practice-list device), in seconds. `null` turns automatic sync off; call `sync()` yourself. |

## FacePing

| Call | Returns | Notes |
|---|---|---|
| `enroll(id, photo)` | `EnrollResult` | Sandbox only. Production enrolment happens with consent on your server or through the FacePing widget. Replaces any face already stored under `id`. |
| `verifyLive(id, cameraRef, { nonce }?)` | `VerifyResult` | A live check on the `<FaceCamera>`: match, a head turn in a random direction, match again. Shows the prompts and sets the guide. About 10 seconds at most. |
| `verify(id, photo, { nonce }?)` | `VerifyResult` | One photo, passive liveness only. |
| `forget(id)` | `boolean` | With a sandbox key: deletes the face now; `false` if there was none. With a device token (production, or a practice-list device): throws `invalidOperation` (remove the person through your server). |
| `forgetAll()` | | Deletes every face on the device now. In production the next sync brings back the people still enrolled. |
| `unpair()` | | Unpairs the device: deletes every face on it and forgets the check-in list it synced, so it can start again with any device token. Moving to another list doesn't need this: start with that list's token and the first successful sync swaps the lists, wiping the old faces first ([Move a device to another list](https://docs.faceping.ai/devices/#move-a-device-to-another-list-or-retire-it)). Use it when a device is retired or handed back, and clear your saved token too. In the sandbox it deletes the faces enrolled on the device. Then `close()` and `init` with the new token. |
| `enrolledIds()` | `string[]` | Who can be verified on this device, as of the last enrol, forget or sync. |
| `sync()` | `SyncResult` | Production: downloads the latest faces for the device's check-in list; a revoked device wipes its faces. Sandbox: activates the key, or renews its licence when due. Either way it refreshes `enrolledIds()`, so it's a good first call when the app starts. |
| `addListener('synced', listener)` | `{ remove() }` | Calls `listener` with a `SyncResult` after every sync, automatic or not. A device syncs at start-up and then every `autoSyncInterval` seconds, so this keeps a status line current. A sandbox key has no automatic sync, so in sandbox mode it fires only after your own `sync()` calls. Call `remove()` on the result when you no longer need the updates. |
| `close()` | | Stops automatic sync and frees the engine. Call `init` again to start over. |

Every call returns a promise, except `addListener`, which returns its subscription straight away.

Keep a check-in device's status line current with `addListener`:

```tsx
useEffect(() => {
  const subscription = FacePing.addListener('synced', (r) => setStatus(`${r.enrolled} people synced (${r.status})`));
  return () => subscription.remove();
}, []);
```

## Photos

A `photo` is any of:

| From | Example |
|---|---|
| The `<FaceCamera>` (takes a still from the live view) | `FacePing.enroll('me', cameraRef)` |
| A file URI (`file://…`, or on Android `content://…`, for example from a photo picker) | `FacePing.enroll('me', uri)` or `{ uri }` |
| Base64 JPEG or PNG (HEIC too on iOS) | `{ base64 }`, or a `data:image/jpeg;base64,…` URI |

Photos are turned upright from their EXIF orientation and scaled down to 1280 pixels on the device before anything else happens.

## FaceCamera

The native front-camera view, with the oval face guide and the liveness prompts ("Turn your head left", "Look back at the camera"). The SDK runs the camera, so you don't need another camera library, and it asks for camera permission the first time the view appears. Give it a size.

```tsx
const camera = useRef<FaceCameraRef>(null);

<FaceCamera ref={camera} style={{ height: 420 }} onCameraFailed={({ message }) => console.warn(message)} />
```

| Prop | Type | Notes |
|---|---|---|
| `showGuide` | `boolean` | The face outline. Default `true`. |
| `onCameraFailed` | `({ message }) => void` | The camera can't start: permission refused or no front camera. The message says which. |
| `style`, `testID` | | As for any view. |

The ref (`FaceCameraRef`) has `setGuideState('ready' | 'working' | 'match' | 'noMatch')` and `startCamera()` (call it if your app gets camera permission another way). `verifyLive` sets the guide for you; set it yourself for other steps, for example `'working'` while enrolling.

To translate or reword the prompts, use the native SDKs' strings: on Android the string resources `faceping_prompt_look_at_camera`, `faceping_prompt_turn_left`, `faceping_prompt_turn_right` and `faceping_prompt_look_back`; on iOS a `FacePing.strings` table with the keys `faceping.prompt.lookAtCamera`, `faceping.prompt.turnLeft`, `faceping.prompt.turnRight` and `faceping.prompt.lookBack`.

## Backups {#android-backup}

The face store's encryption keys stay in the phone's Keychain or Keystore, so a backed-up copy couldn't be read anywhere else. On iOS, FacePing's folder is already excluded from backups.

On Android, the Expo config plugin adds backup rules for you: `faceping_data_extraction_rules.xml` (Android 12 and later, cloud backups and phone-to-phone transfers) and `faceping_backup_rules.xml` (Android 11 and earlier), which leave out FacePing's data. Keep `"android": { "allowBackup": false }` in `app.json` as well. To keep your own rules instead, set `"androidBackupRules": false` in the plugin's options. If your app already sets `android:dataExtractionRules` or `android:fullBackupContent`, the plugin leaves them alone: add FacePing's two excludes to yours, in both `<cloud-backup>` and `<device-transfer>`:

```xml
<exclude domain="file" path="faceping/"/>
<exclude domain="sharedpref" path="faceping.keys.xml"/>
```

A bare React Native app adds the same two excludes to its own `data_extraction_rules.xml` and `backup_rules.xml`.

## Results

```ts
type EnrollResult = {
  outcome: 'enrolled' | 'noFace' | 'multipleFaces' | 'faceTooSmall' | 'notLive' | 'limitReached';
  id: string;
  isEnrolled: boolean;
};

type VerifyResult = {
  outcome: 'match' | 'noMatch' | 'notEnrolled' | 'noFace' | 'livenessFailed'
         | 'challengeFailed' | 'expired' | 'leaseExpired';
  similarity: number;           // cosine similarity; the match threshold is 0.363
  livenessScore: number | null; // passive liveness of the deciding frame
  elapsedMs: number;            // how long the check took on the device
  isSandbox: boolean;   // true with a sandbox key; false with a device token, even for a practice list
  isMatch: boolean;
  signedResult: string | null;  // check-in devices: the signed result for your server; null in the sandbox
};

type SyncResult = {
  status: 'ok' | 'gone' | 'revoked' | 'unavailable';
  enrolled: number;
  leaseUntil: Date | null;      // production: verifies offline until then
  deleteAfter: Date | null;
  signing: 'registered' | 'mismatch' | 'unknown';
};
```

What a sync status means, with a device token:

| Status | What happened | What the app should do |
|---|---|---|
| `'ok'` | The device has the list's latest faces. | Nothing: it verifies offline until the lease runs out. |
| `'gone'` | The list is past its deletion date, so the device wiped its copy. | Stop offering face check-in for this list. |
| `'revoked'` | The device token was revoked, isn't valid, or its list was deleted, so the device wiped its copy. | Stop offering face check-in, and pair the device again with a new token if it should carry on. |
| `'unavailable'` | No connection, or the server couldn't be reached. The device keeps its copy. | Carry on: it verifies offline until the lease runs out, then needs a sync. |

`signedResult` is set on a check-in device (a device token): every outcome is signed by the device, so your server can prove the check happened. It's `null` in the sandbox, and until the device's first sync. Pass `{ nonce }` from your server to bind it to that check (1 to 128 characters, no control characters). `signing` says whether FacePing holds the device's signing key: `'registered'`; `'mismatch'` (the app was reinstalled or its data cleared, so checks still work but signed results won't verify: add the device again); or `'unknown'` (before the first sync, and in the sandbox). The types are exported as `VerifyOptions` and `SigningState`. See [Signed check results](https://docs.faceping.ai/signed-results/).

The outcome types are exported as `EnrollOutcome` and `VerifyOutcome`. `limitReached` means the sandbox already holds 25 faces on this device: forget one first. `leaseExpired` (production) means the device hasn't synced for longer than its lease, 24 hours by default; it needs a connection before it verifies again.

## Errors

Set-up and device problems throw a `FacePingError` with a `message` ready to show and a `code`. `isFacePingError(e, 'setup')` checks for one.

| Code | When |
|---|---|
| `setup` | The key or token is missing or malformed (neither set, both set, or a sandbox key that doesn't start with `fp_test_`), or the sandbox key couldn't be activated (the first run needs a connection, or the server refused the key), or `init` hasn't been called. A revoked or mistyped device token throws this at a device's first sync; once a device has synced, a revoked token or a deleted list doesn't throw: sync returns `'revoked'` and the device wipes its copy. |
| `model` | The face models couldn't load on this device. Send people to your normal way in. |
| `invalidOperation` | Not allowed in this mode or state, for example enrolling on the device in production. |
| `invalidArgument` | A bad argument: an empty id, a photo that isn't a readable image, or a nonce that isn't 1 to 128 characters. |
| `storage` | The device's secure storage failed. |
| `camera` | The camera couldn't start or didn't deliver a picture, or the `<FaceCamera>` isn't on screen. |
| `unknown` | Anything else. The message says what. |

Everything else is a result, not an exception: a face check never throws because someone looked away.
