# Mobile apps

> Search an index from an iOS or Android app with its public ID: list the app's IDs, then search with SearchNativeClient in React Native and Expo, or over HTTP from Swift, Kotlin and Flutter.

A mobile app searches with the index's public ID, as a website does. Apps send no `Origin` header, so the index lists the app instead of a site: its iOS bundle ID and its Android application ID. Every request from the app names it in an `x-findlane-app` header.

Everything browser search does works from an app: searches with their [subindexes](/docs/subindexes.md), did you mean, [query suggestions](/docs/search.md#query-suggestions) and popular searches, multi-index searches, [lists](/docs/lists.md), [recommendations](/docs/recommendations.md) and [events](/docs/events.md).

## List your app

On the index's **Public access** page, add each of the app's IDs under **Apps**, such as `io.example.app`:

- The iOS bundle ID and the Android application ID. List both when they differ.
- An ID has at least two parts separated by dots, of letters, digits, `-` and `_`, and starts with a letter.
- An index lists up to 10 apps. Changes apply within a minute.
- [Subindexes](/docs/subindexes.md) use their index's apps, as they use its allowed origins.

Your AI assistant can list them too: [`set_allowed_origins`](/docs/agents.md) takes `apps`. Browser search is on while an index lists at least one origin or app.

> **Warning:** Never put an API key in an app. It works, since the API turns keys away only from web pages, and anyone can extract it from the app and use it as your server would. The public ID is made for this: it only searches, only this index, and only what its [public settings](/docs/security.md#what-browser-search-can-read) return.

## React Native and Expo

### Install

```sh
npm install @findlane/browser
```

The app imports `@findlane/browser/native`, which needs Metro to resolve package exports. Metro does from React Native 0.79 (Expo SDK 53); before that, turn on `resolver.unstable_enablePackageExports` in `metro.config.js`.

### Create a client

```ts
import { Platform } from "react-native"
import { SearchNativeClient } from "@findlane/browser/native"

export const client = new SearchNativeClient({
  publicId: "pub_your_public_id",
  app: Platform.OS === "android" ? "io.example.android" : "io.example.app",
})
```

`SearchNativeClient` is the [browser SDK's client](/docs/browser-sdk.md#create-a-client), with what an app needs:

- It names the app in every request, events included.
- Waiting events go when the app goes to the background or becomes inactive, as a page's go when it's hidden.
- It keeps recent searches, visitor IDs and its A/B test label in memory until the app closes, unless you give it `storage`.
- In an Expo app's web build (`Platform.OS` is `web`), it searches as a page does, so list that site's origin too.

It takes the browser SDK's other options, such as `visitorIds` and `signedKey`, and `@findlane/browser/native` exports everything `@findlane/browser` does.

### Keep what it remembers

`storage` is any synchronous store with `getItem`, `setItem` and `removeItem`. With expo-sqlite's key-value store:

```ts
import Storage from "expo-sqlite/kv-store"

export const client = new SearchNativeClient({
  publicId: "pub_your_public_id",
  app: "io.example.app",
  visitorIds: true,
  storage: {
    getItem: (key) => Storage.getItemSync(key),
    setItem: (key, value) => Storage.setItemSync(key, value),
    removeItem: (key) => Storage.removeItemSync(key),
  },
})
```

MMKV works the same way, with its own get, set and delete methods. The client then keeps recent searches, the visitor ID, the visit ID with its 30-minute window, the A/B test label, and where the index's [optimized images](/docs/images.md) load from between launches.

### A search box

The [React hooks](/docs/react.md#your-own-markup) work in React Native. Pass the client to `FindlaneProvider`, and `navigate` to `useAutocomplete`, so a chosen result opens through your router rather than `window.location`:

```tsx
import { router } from "expo-router"
import { FlatList, Pressable, Text, TextInput } from "react-native"
import { FindlaneProvider, useAutocomplete } from "@findlane/browser/react"
import { client } from "./search-client"

export function SearchScreen() {
  return (
    <FindlaneProvider client={client}>
      <SearchBox />
    </FindlaneProvider>
  )
}

function SearchBox() {
  const box = useAutocomplete<{ name: string }>({
    querySuggestions: 5,
    popularSearches: 6,
    recentSearches: true,
    subindexes: {
      guilds: { limit: 3, getHref: (hit) => `/guild/${hit.id}` },
      items: { limit: 3, getHref: (hit) => `/item/${hit.id}` },
    },
    getHref: (hit) => `/character/${hit.id}`,
    navigate: (href) => router.push(href),
  })
  return (
    <>
      <TextInput
        value={box.query}
        onChangeText={box.setQuery}
        onFocus={box.focus}
        onBlur={box.blur}
        placeholder="Search"
        autoCorrect={false}
      />
      <FlatList
        data={box.items}
        keyExtractor={(item) => String(item.index)}
        keyboardShouldPersistTaps="handled"
        renderItem={({ item }) => (
          <Pressable onPress={() => box.choose(item.index)}>
            <Text>{item.kind === "hit" || item.kind === "subindex" ? String(item.hit.record.name)
              : item.kind === "facetMatch" ? item.match.label : item.q}</Text>
          </Pressable>
        )}
      />
    </>
  )
}
```

`items` lists the query suggestions, or with an empty box the recent and popular searches, then each subindex's results, then the index's, all from one search. `choose` runs a search or opens a result: a search fills the box, and a result goes to `navigate` with its `getHref`. `focus` and `blur` stand in for an input's events, so an empty box shows the popular and recent searches. `highlightParts` turns a hit's highlights into parts to draw with `<Text>`.

`useSearch` and `SearchProvider` work too, with `routing` left off. The components, such as `SearchBox` and `Hits`, draw web pages' elements, so an app draws its own.

### Without the hooks

The client's methods are the [browser SDK's](/docs/browser-sdk.md). One search with its subindexes, and the suggestions for a search box:

```ts
const results = await client.search({
  q: "ragnaros",
  limit: 6,
  subindexes: { guilds: { limit: 3 }, items: { limit: 3 }, quests: { limit: 3 }, pages: { limit: 3 } },
})
results.hits                     // the index's
results.subindexes?.guilds       // { hits, total, … }

const suggestions = await client.querySuggestions({ q: "rag", limit: 5 })
const popular = await client.popularSearches({ limit: 6 })
```

## Swift, Kotlin and Flutter

Apps that don't use React Native search over HTTP. Every request names the app in `x-findlane-app`, and sends its JSON body as `text/plain`, as the SDK does:

| Request                                                       |                                                                                                |
| ------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- |
| `POST /api/public/indexes/{publicId}/search`                  | A [search](/docs/search.md), with any subindexes it asks for                                      |
| `POST /api/public/indexes/{publicId}/suggest`                 | Did you mean, for a search that found nothing                                                  |
| `POST /api/public/indexes/{publicId}/query-suggestions`       | Query suggestions for `{ "q": "rag", "limit": 5 }`; popular searches for `{ "q": "", "limit": 6 }` |
| `POST /api/public/indexes/{publicId}/recommendations`         | A product's [recommendations](/docs/recommendations.md): `{ "objectID": "…" }`                     |
| `GET /api/public/indexes/{publicId}/lists/{id}`, `GET …/lists?ids=…` | The index's [lists](/docs/lists.md)                                                         |
| `POST /api/public/indexes/{publicId}/events`                  | [Events](/docs/events.md): `{ "events": [ … ] }`                                                   |
| `POST /api/public/search`                                     | A multi-index search: `{ "queries": [{ "index": "pub_…", "q": "…" }] }`. Each index must list the app. |

All of them are at `https://api.findlane.dev`. In Swift:

```swift
var request = URLRequest(url: URL(string: "https://api.findlane.dev/api/public/indexes/pub_your_public_id/search")!)
request.httpMethod = "POST"
request.setValue("text/plain", forHTTPHeaderField: "Content-Type")
request.setValue("io.example.app", forHTTPHeaderField: "x-findlane-app")
request.httpBody = try JSONSerialization.data(withJSONObject: ["q": "rain jacket", "limit": 10])
let (data, _) = try await URLSession.shared.data(for: request)
```

In Kotlin, with OkHttp:

```kotlin
val request = Request.Builder()
  .url("https://api.findlane.dev/api/public/indexes/pub_your_public_id/search")
  .header("x-findlane-app", "io.example.android")
  .post("""{"q":"rain jacket","limit":10}""".toRequestBody("text/plain".toMediaType()))
  .build()
val json = client.newCall(request).execute().use { it.body!!.string() }
```

In Flutter, with `package:http`:

```dart
final response = await http.post(
  Uri.parse('https://api.findlane.dev/api/public/indexes/pub_your_public_id/search'),
  headers: {'content-type': 'text/plain', 'x-findlane-app': 'io.example.app'},
  body: jsonEncode({'q': 'rain jacket', 'limit': 10}),
);
```

The answers are the [API's](/docs/api.md#search). A request without the header, or naming an app the index doesn't list, is refused with `403`.

## Logged-in people

For people who log in, such as subscribers, your server signs a key for each of them, as for a website: see [Logged-in visitors](/docs/security.md#logged-in-visitors). The app fetches it from your server with the person's session, and sends it with the app's header:

```ts
export const client = new SearchNativeClient({
  publicId: "pub_your_public_id",
  app: "io.example.app",
  signedKey: () => fetch("https://example.com/api/search-key", { headers: { authorization: `Bearer ${session.token}` } })
    .then((response) => response.text()),
})
```

Over HTTP, put it in the search's body as `signedKey`.

## What apps' searches get

- **Limits:** a visitor's: 240 searches a minute per address by default, and results up to 1,000 deep. See [Bots and rate limits](/docs/security.md#bots-and-rate-limits).
- **Traffic:** Android apps' HTTP clients (OkHttp, and Dart's in Flutter) count as visitors for a listed app, and iOS apps' already do. Other clients keep their class, so a script naming your app is still a script.
- **Events** count as shoppers', as a page's do.
- **Analytics:** on the [Traffic tab](/docs/analytics.md#traffic), apps' searches are their own row, **Apps**, and the sites list shows each app beside your websites. Search analytics count them with your visitors', and the traffic source **Apps** shows your apps' searches and events alone, **Websites** your websites'.
- **The cache:** apps share the cached answers your site's searches get.

Rotating the public ID stops the apps already installed until they update, so ship the new ID in an app release first.
