---
title: "Native apps"
description: "Sign in to a wervt app from an iOS or Android app, call its API, sync offline writes and send feedback."
canonical_url: "https://docs.dev.lightdrop.cloud/guides/native-apps"
---
# Native apps

> Sign in to a wervt app from an iOS or Android app, call its API, sync offline writes and send feedback.

A native app (Expo / React Native, Swift, Kotlin, …) uses a wervt app as its backend. It signs in
with the normal wervt login, gets an access token for that app and calls the app's API routes with
it. The runtime checks the token on every path and hands the app its user, so the server code is
the same as for the web: `useWervtUser(event)` returns the person, private apps check their list.

The examples use Expo with [`@wervt/expo`](https://www.npmjs.com/package/@wervt/expo), which does
the sign-in, keeps the tokens in the keychain / keystore, refreshes them and calls the app's API.
Other stacks (Swift, Kotlin, plain `expo-auth-session`) follow the same steps with their OAuth
library; [What the SDK does](#what-the-sdk-does) lists what they have to get right.

```bash
npx expo install @wervt/expo expo-auth-session expo-secure-store expo-web-browser expo-crypto
```

## Sign in

wervt's login (`auth.dev.lightdrop.cloud`) is an OAuth 2.1 / OpenID Connect server. A native app is a
**public client**: no secret, PKCE instead.

<table>
<thead>
  <tr>
    <th>
      What
    </th>
    
    <th>
      Value
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      Issuer
    </td>
    
    <td>
      <code>
        https://auth.dev.lightdrop.cloud/api/auth
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      Discovery
    </td>
    
    <td>
      <code>
        https://auth.dev.lightdrop.cloud/api/auth/.well-known/openid-configuration
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      Scopes
    </td>
    
    <td>
      <code>
        openid profile email offline_access
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      Token audience
    </td>
    
    <td>
      <code>
        resource=https://<app>.dev.lightdrop.cloud
      </code>
    </td>
  </tr>
</tbody>
</table>

<warning>

The discovery document lives under `/api/auth`. `https://auth.dev.lightdrop.cloud/.well-known/openid-configuration`
is a 404. Libraries that take an issuer (`fetchDiscoveryAsync(issuer)` in `expo-auth-session`)
need exactly `https://auth.dev.lightdrop.cloud/api/auth`.

</warning>

### Register the client

Register the app once with the CLI and keep the client id it prints in the app's config. The
client belongs to the wervt app: its owner and members can list and delete it, also in the
dashboard (the app's **Native apps** section).

```bash
wervt clients create todos --name "Todos for iOS" --redirect dev.example.todos:/auth
wervt clients list todos
wervt clients delete todos <client_id>   # signs out every install that used it
```

Without the CLI, register through the `registration_endpoint` of the discovery document (dynamic
client registration, no account needed). Such a client belongs to no app; an admin can assign it
with `wervt clients link <app> <client_id>`.

```bash
curl -X POST https://auth.dev.lightdrop.cloud/api/auth/oauth2/register \
  -H 'Content-Type: application/json' \
  -d '{
    "client_name": "Todos for iOS",
    "redirect_uris": ["dev.example.todos:/auth"],
    "token_endpoint_auth_method": "none",
    "grant_types": ["authorization_code", "refresh_token"],
    "response_types": ["code"],
    "scope": "openid profile email offline_access"
  }'
```

The redirect URI must be a private-use scheme as [RFC 8252](https://www.rfc-editor.org/rfc/rfc8252#section-7.1)
asks of native apps: a **reverse domain name** you control, and **no authority**, so a single
slash after the colon. `dev.example.todos:/auth` works; `todos://auth` and
`dev.example.todos://auth` are rejected with `invalid_redirect_uri`.

The scheme must also be registered with the OS. The `@wervt/expo` config plugin adds it to the
app's `scheme` (next to any short scheme it already has for deep links) and fails the build on
redirect URIs the login would reject:

```json [app.json]
{
  "expo": {
    "scheme": "todos",
    "plugins": [["@wervt/expo", { "redirectUri": "dev.example.todos:/auth" }], "expo-secure-store"]
  }
}
```

Without the plugin, list both schemes yourself: `"scheme": ["todos", "dev.example.todos"]`.

### Ask for a token for the app

The token has to be for the app: `resource=https://<app>.dev.lightdrop.cloud` goes with the authorize request,
the code exchange **and** every refresh. Without it the token's audience doesn't match the app and
the runtime ignores it. A token for the whole app is accepted on every path; a token for
`https://<app>.dev.lightdrop.cloud/mcp` works too. The first sign-in registers the app as a token audience,
which needs `@wervt/nuxt` on Nuxt 5 (it serves the app's `/.well-known/oauth-protected-resource`).

`@wervt/expo` takes care of that. Create one client for the app:

```ts [src/wervt.ts]
import { createWervtClient } from '@wervt/expo'

export const wervt = createWervtClient({
  app: 'https://todos.dev.lightdrop.cloud',
  /** From the registration above; public by design (PKCE, no secret). */
  clientId: '<client_id>',
  redirectUri: 'dev.example.todos:/auth',
})
```

`signIn()` opens the login in the system browser sheet, with PKCE, and stores the tokens in the
keychain / keystore. It resolves `false` when the person cancels. `useUser()` follows the session:

```tsx [src/account.tsx]
import { Button, Text } from 'react-native'
import { wervt } from './wervt'

export function Account() {
  const { loading, signedIn, user } = wervt.useUser()
  if (loading) return null
  if (!signedIn) return <Button title="Sign in" onPress={() => wervt.signIn()} />
  return (
    <>
      <Text>{user?.name ?? user?.email}</Text>
      <Button title="Sign out" onPress={() => wervt.signOut()} />
    </>
  )
}
```

`user` (`id`, `email`, `name`, `image`) comes from the ID token, so it's there offline too; `id`
is the same as `useWervtUser(event).id` on the server. The options, the web behavior and the
lower-level helpers are in the [package README](https://github.com/wervt-app/wervt/tree/main/packages/expo#readme).

### What the SDK does

The parts that matter, for `@wervt/expo` and for any other client:

- Refresh before the token expires (a minute ahead), not only after a 401.
- Share one in-flight refresh. Refresh tokens rotate; two refreshes with the same token race, and
the login only forgives reusing a just-rotated token within 30 seconds.
- Sign out only when the login rejects the refresh token (`invalid_grant`). Offline or a flaky token
endpoint must keep the session, or a phone without network signs its person out.
- `offline_access` is what gets a refresh token at all.

`wervt.onSignOut((reason) => …)` reports a rejected refresh token as `'expired'`, e.g. to show the
sign-in again or clear cached data.

<note>

Expo Go can't receive the custom-scheme redirect, so the sign-in only works in a real build
(a development build or a release build, see [Expo pitfalls](#appendix-expo-pitfalls)). Keep the
rest of the app usable signed out so it can still be tried in Expo Go.

</note>

## Call the app's API

`wervt.fetch` sends the token as `Authorization: Bearer <token>`, and only to the app's origin. On a
401 it refreshes once and retries; only then it gives up. Plain objects go out as JSON, the answer
comes back parsed:

```ts
import { WervtApiError, WervtSignedOutError } from '@wervt/expo'
import { wervt } from './wervt'

const me = await wervt.fetch<{ id: string; name: string }>('/api/me')
await wervt.fetch('/api/todos', { method: 'POST', body: { title: 'Milk' } })

try {
  await wervt.fetch('/api/todos/42', { method: 'DELETE' })
} catch (error) {
  if (error instanceof WervtSignedOutError) {
    // no session (any more): show the sign-in
  } else if (error instanceof WervtApiError) {
    // error.status, error.message (the route's `message`), error.data
  } else {
    // network error: the session is kept, try again later
  }
}
```

For requests `wervt.fetch` doesn't cover (uploads through another library, a WebSocket), take
`await wervt.getAccessToken()` and send it the same way.

The session cookie wins when a request has both. Bearer tokens that aren't wervt access tokens
(an app's own API tokens) reach the app untouched.

On the server nothing changes: the runtime verified the token before the request reached the app,
and `useWervtUser(event)` returns the same user as with the session cookie. On a private app a
missing or invalid token gets a 401 with `WWW-Authenticate` instead of the login redirect, and
people not on the list get a 403. On a public app an invalid token just means no user: the route
decides (usually a 401 of its own).

### `/api/me`: the profile on first call

Apps usually keep their own row per person (a player, a profile, settings). Create it on the first
request instead of in a separate sign-up step, so the web and the native app can come first:

```ts [server/utils/profile.ts]
import { useDb, useWervtUser } from '@wervt/nuxt/server'
import { eq } from 'drizzle-orm'
import { createError, type RequestEvent } from 'nuxt/server'
import { profiles } from '../db/schema'

export async function currentProfile(event: RequestEvent) {
  const user = useWervtUser(event)
  if (!user) throw createError({ status: 401, message: 'Sign in first.' })
  const db = useDb()
  const [existing] = await db.select().from(profiles).where(eq(profiles.userId, user.id))
  if (existing) return existing
  const [created] = await db
    .insert(profiles)
    .values({ userId: user.id, email: user.email, name: user.name ?? user.email })
    // The app and the web may both make their first request at once.
    .onConflictDoNothing({ target: profiles.userId })
    .returning()
  if (created) return created
  const [raced] = await db.select().from(profiles).where(eq(profiles.userId, user.id))
  return raced!
}
```

```ts [server/api/me.get.ts]
import { defineEventHandler } from 'nuxt/server'
import { currentProfile } from '../utils/profile'

export default defineEventHandler(async (event) => {
  const { id, name, email } = await currentProfile(event)
  return { id, name, email }
})
```

`userId` needs a unique index for `onConflictDoNothing`. Every other route starts with
`currentProfile(event)` too.

### REST for the app, shapes for the web

[Live data](https://docs.dev.lightdrop.cloud/guides/live-data) (`useShape`) is made for the Vue app. A native app is better served
by plain JSON routes: `GET` routes that return exactly what a screen needs, and the same `POST` /
`PATCH` routes the web uses for writes. Writes from the app still show up live in every open
browser tab, because shapes follow the database, not the client.

## Offline writes

Phones lose their connection. For data that must not get lost (a finished game, a form, a
measurement), write to a local outbox first and send it when the app is online:

- Give every entry a **client id** when it's created (an install id plus the entry's own id), and
store it with a unique index on the server. A retry of an entry the server already has returns
the stored result instead of creating a duplicate.
- Send the queue in order. A 4xx other than 401 means the server rejected the entry for good:
mark it failed and drop it. A network error or 401 affects every entry: stop and retry later.
- Never trust the uploaded result. **Validate it again on the server**: run the uploaded input
through the same rules (ideally the same code, see [below](#share-code-with-the-server)) and store
what comes out, not what the app claimed.

```ts [src/outbox.ts]
import { WervtApiError } from '@wervt/expo'
import { wervt } from './wervt'
import { load, save } from './storage' // persisted, e.g. expo-sqlite's kv-store

type Pending = { clientId: string; body: Record<string, unknown> }

let queue: Pending[] = load()

export function enqueue(clientId: string, body: Record<string, unknown>) {
  queue = [...queue.filter((p) => p.clientId !== clientId), { clientId, body }]
  save(queue)
  void flush()
}

export async function flush() {
  for (const entry of [...queue]) {
    try {
      await wervt.fetch('/api/results', { method: 'POST', body: { clientId: entry.clientId, ...entry.body } })
    } catch (error) {
      // WervtSignedOutError and network errors land here too: retry the whole queue later.
      const final = error instanceof WervtApiError && error.status >= 400 && error.status < 500 && error.status !== 401
      if (!final) return
    }
    queue = queue.filter((p) => p.clientId !== entry.clientId)
    save(queue)
  }
}
```

```ts [server/api/results.post.ts]
// Imports as in the routes above; `input` is the valibot schema of the raw input.
export default defineEventHandler(async (event) => {
  const me = await currentProfile(event)
  const body = await useValidatedBody(event, { clientId: v.pipe(v.string(), v.maxLength(80)), input })
  const [known] = await useDb().select().from(results).where(eq(results.clientId, body.clientId))
  if (known) return { id: known.id, duplicate: true }
  // Recomputed from the raw input with the shared code; throws a 422 for anything invalid.
  const result = evaluate(body.input)
  // … insert with clientId, recordedBy: me.id
})
```

Call `flush()` on app start, when the app comes back to the foreground and after sign-in. A short
delay before the first send gives people a window to undo a mistake on the result screen.

## Share code with the server

When the server re-validates what the app computed, both need the same logic (rules, scoring,
validation). Options, from most to least integrated:

- **One repository with a pnpm workspace**: the Expo app, the wervt app and a shared package
(`packages/core`) side by side. Both import the package; Metro follows workspace packages since
Expo SDK 52 without extra config.
- **A shared package** published to a registry, when the two live in separate repositories and
change rarely.
- **A copy script**, when the app owns the logic and the server only replays it. Write a header into
every copied file so nobody edits the copy:```bash [scripts/sync-core.sh]
#!/usr/bin/env bash
# The rules live in the Expo app; the server replays uploads with the same code.
set -euo pipefail
here="$(cd "$(dirname "$0")/.." && pwd)"
src="${1:-$here/../todos-app/src/core}"
for f in rules.ts score.ts; do
  { echo "// Copied from the app by scripts/sync-core.sh. Edit it there, not here."; cat "$src/$f"; } \
    > "$here/shared/core/$f"
done
```

<br />

Put the copy in `shared/` of the wervt app (Nuxt's folder for code used by app and server) and
keep it pure: no React, no Expo or Node APIs, nothing that touches storage.

<warning>

Nuxt, and so every wervt app, type-checks with `noUncheckedIndexedAccess`: `array[i]` is
`T | undefined`. Expo projects don't turn it on by default, so code that passes `tsc` in the app can
fail `vp check` on the server. Write shared code for the stricter setting, or turn it on in the
app's `tsconfig.json` too.

</warning>

## Feedback from the app

The [feedback widget](https://docs.dev.lightdrop.cloud/guides/feedback) is for web pages, but its endpoint works from native code.
kontor's intake API accepts requests without an `Origin` header, so a native app posts straight to
it with the project's public intake key:

```ts [src/feedback.ts]
import Constants from 'expo-constants'
import { Platform } from 'react-native'

const FEEDBACK_URL = 'https://kontor.wervt.app/api/intake/pk_…'

export async function sendFeedback(input: { title: string; description: string; name?: string; email?: string }) {
  const response = await fetch(FEEDBACK_URL, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
    body: JSON.stringify({
      ...input,
      // Shown to the team only: whatever helps to reproduce.
      context: {
        app: `Todos ${Constants.expoConfig?.version ?? '?'}`,
        platform: `${Platform.OS} ${Platform.Version}`,
      },
    }),
  })
  if (!response.ok) {
    const body = (await response.json().catch(() => null)) as { message?: string } | null
    throw new Error(body?.message ?? `HTTP ${response.status}`)
  }
  return (await response.json()) as { identifier: string }
}
```

<table>
<thead>
  <tr>
    <th>
      Field
    </th>
    
    <th>
      Type
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        title
      </code>
    </td>
    
    <td>
      Required, up to 250 characters
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        description
      </code>
    </td>
    
    <td>
      Markdown
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        name
      </code>
    </td>
    
    <td>
      Up to 80 characters
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        email
      </code>
    </td>
    
    <td>
      A valid address or <code>
        ''
      </code>
      
       (required when the key asks for it)
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        context
      </code>
    </td>
    
    <td>
      Record of strings, at most 20 entries (keys up to 40, values up to 1000 characters)
    </td>
  </tr>
</tbody>
</table>

Too many reports for a key in a short time get a 429.

<note>

Reports from a native app aren't linked to the reporter's wervt account yet: the app's token is
only valid for its own app, not for kontor. Send the name and email from the app's own profile
(`/api/me`) instead; they show up as the reporter. Linking native reports to the account is
planned.

</note>

## Over-the-air updates

JavaScript and asset changes can reach installed apps from wervt, without a store release: see
[Over-the-air updates](https://docs.dev.lightdrop.cloud/guides/updates).

## Appendix: Expo pitfalls

Not wervt-specific, but each of these cost time on the first wervt-backed Expo app.

### iOS 27 needs the scene life cycle

iOS 27 aborts apps at launch that don't adopt the scene life cycle, and the SDK 57 prebuild
template still starts React Native from the app delegate. Builds made with `expo prebuild` crash
right after the splash screen. A config plugin wires up Expo's own `ExpoAppSceneDelegate`:

```js [plugins/with-scene-lifecycle.js]
// iOS 27 asserts at launch unless an app adopts the scene life cycle, and the SDK 57 prebuild
// template still starts React Native from the app delegate. The scene manifest points UIKit at
// ExpoAppSceneDelegate; the app delegate only creates the React Native factory it starts.
const { withAppDelegate, withInfoPlist } = require('expo/config-plugins')

const START_IN_APP_DELEGATE =
  /#if os\(iOS\) \|\| os\(tvOS\)\n\s*window = UIWindow\(frame: UIScreen\.main\.bounds\)\n\s*factory\.startReactNative\([\s\S]*?\)\n#endif\n/

module.exports = function withSceneLifecycle(config) {
  config = withInfoPlist(config, (mod) => {
    mod.modResults.UIApplicationSceneManifest = {
      UIApplicationSupportsMultipleScenes: false,
      UISceneConfigurations: {
        UIWindowSceneSessionRoleApplication: [
          {
            UISceneConfigurationName: 'Default Configuration',
            UISceneDelegateClassName: 'EXExpoAppSceneDelegate',
          },
        ],
      },
    }
    return mod
  })

  return withAppDelegate(config, (mod) => {
    if (mod.modResults.language !== 'swift') throw new Error('with-scene-lifecycle expects a Swift AppDelegate')
    let source = mod.modResults.contents
    if (!source.includes('ExpoReactNativeFactoryProvider')) {
      source = source.replace(
        'class AppDelegate: ExpoAppDelegate {',
        'class AppDelegate: ExpoAppDelegate, ExpoReactNativeFactoryProvider {',
      )
    }
    if (!START_IN_APP_DELEGATE.test(source) && !source.includes('ExpoAppSceneDelegate starts')) {
      throw new Error('with-scene-lifecycle: the AppDelegate template changed, check the patch')
    }
    source = source.replace(
      START_IN_APP_DELEGATE,
      "    // ExpoAppSceneDelegate starts React Native into the scene's window.\n",
    )
    mod.modResults.contents = source
    return mod
  })
}
```

Add `"./plugins/with-scene-lifecycle"` to `plugins` in `app.json`. The plugin fails loudly when a
later SDK changes the template, which is the moment to check whether it's still needed.

### Device builds without EAS

A release build straight onto a cabled iPhone, signed with your team; the two `-allow…` flags let
Xcode create the profile and register a new device on its own:

```bash
npx expo prebuild -p ios --clean
cd ios && xcodebuild -workspace Todos.xcworkspace -scheme Todos -configuration Release \
  -destination 'generic/platform=iOS' -derivedDataPath build \
  -allowProvisioningUpdates -allowProvisioningDeviceRegistration DEVELOPMENT_TEAM=<team id>
xcrun devicectl list devices   # the iPhone's UDID
xcrun devicectl device install app --device <UDID> build/Build/Products/Release-iphoneos/Todos.app
```

To register a device that isn't in the team yet, build once with `-destination id=<UDID>`.

### EAS Update

```json [app.json]
{
  "expo": {
    "runtimeVersion": { "policy": "fingerprint" },
    "updates": {
      "url": "https://u.expo.dev/<project id>",
      "requestHeaders": { "expo-channel-name": "preview" }
    }
  }
}
```

- The `fingerprint` policy changes the runtime version whenever native code changes (a new
`expo-*` package, a config plugin, native fields in `app.json`). Old builds then stop getting
updates until they're rebuilt, instead of loading JS they can't run.
- The fingerprint also hashes `eas.json`, `.easignore` and `.gitignore`. Editing a build profile or
an ignore file then looks like a native change and cuts every installed build off from updates.
Keep them out with a `.fingerprintignore` in the project root:```txt [.fingerprintignore]
eas.json
.easignore
.gitignore
```

<br />

Check with `npx expo-updates fingerprint:generate --platform ios` before and after such an edit.
- Builds made by EAS get their channel from `eas.json`. Local builds (`xcodebuild`,
`expo run:*`) don't: `updates.requestHeaders` pins them to a channel.
- `eas update` in non-interactive mode (agents, CI) needs `--environment` next to `--channel`:```bash
npx eas-cli@latest update --channel preview --environment preview --message "…" --non-interactive
```

### Files that stay out of git but must reach EAS

EAS uploads the project as git sees it, so files in `.gitignore` never reach the build. When some
assets are imported locally and must stay out of the repository (licensed sounds, fonts), add an
`.easignore`: a copy of `.gitignore` without those lines. EAS uses it instead of `.gitignore`.

### Typed routes

With `experiments.typedRoutes`, Expo Router regenerates the route types only while Metro runs.
After adding or renaming a screen, start `npx expo start` once before running `tsc`, or type
checks fail on the new `href`.


## Sitemap

See the full [sitemap](https://docs.dev.lightdrop.cloud/sitemap.md) for all pages.
