# Mobile \[Sign a user in from an Expo app, in an authentication sheet over the app.]

## Overview

An Expo app signs in through the redirect flow in the system browser, not a web view, so the app never sees the user's credentials. The <SourceLink name="expo" path="src/plugins/expo.ts">`expo`</SourceLink> preset shows Tempo ID's pages in an authentication sheet over the app, and keeps the [session](/docs/guides/user-session) in the device's secure store. It is the sign-in flow for Expo, and a React Native app without Expo uses the [same plugin](/docs/guides/mobile#sign-in-without-expo).

A custom scheme is not an origin, so the app needs a [registration](https\://github.com/tempoxyz/id/blob/main/docs/apps.md#registration) with Tempo ID, which issues its client ID and lists its redirect URI.

An Expo app runs only on a device, so the page holds no demo. This component runs the whole flow\: a sign-in, the session, and a sign-out.

:::code-group
```tsx [App.tsx]
import { Button, Text, View } from 'react-native'
import { accounts } from './tempo.config.js'

export function App() {
  const { isPending, session } = accounts.useSession()

  if (isPending) return null
  if (!session)
    return (
      <Button
        onPress={() => accounts.redirect.signIn()}
        title="Sign in with Tempo"
      />
    )

  return (
    <View>
      <Text>Signed in as {session.user.email}</Text>
      <Button onPress={() => accounts.signOut()} title="Sign out" />
    </View>
  )
}
```

```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { expo } from 'accounts/expo'
import { react } from 'accounts/react'

export const accounts = Accounts.create({
  // Each sign-in requests an access key that sends up to 100 OUSD for a day.
  accessKey: () => ({
    expiry: '1d',
    limits: [{ limit: '100', token: 'ousd' }],
  }),
  chain: 'testnet',
  // The client ID of the app's registration.
  clientId: 'example-mobile',
  plugins: [expo({ redirectUri: 'com.example.app:/callback' }), react()],
})
```
:::

## Walkthrough

The [`mobile`](https\://github.com/tempoxyz/accounts/tree/main/examples/mobile) example runs these steps. The React Native tab of [Getting started](/#walkthrough) installs the packages, sets the app's scheme, and configures Metro.

::::steps
### Create the instance

<SourceLink name="expo" path="src/plugins/expo.ts">`expo`</SourceLink> returns two plugins. The first sets the instance's store to the secure store, and its <SourceLink name="expo.redirectUri" path="src/plugins/expo.ts">`redirectUri`</SourceLink> on the app's scheme. The second is the <SourceLink name="redirect" path="src/plugins/redirect.ts">`redirect`</SourceLink> plugin, whose sign-in opens the sheet.

```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { expo } from 'accounts/expo'
import { react } from 'accounts/react'

export const accounts = Accounts.create({
  // Each sign-in requests an access key that sends up to 100 OUSD for a day.
  accessKey: () => ({
    expiry: '1d',
    limits: [{ limit: '100', token: 'ousd' }],
  }),
  chain: 'testnet',
  // The client ID of the app's registration.
  clientId: 'example-mobile',
  plugins: [expo({ redirectUri: 'com.example.app:/callback' }), react()],
})
```

For a local Tempo ID or another chain, [Use another Tempo ID or chain](/docs/guides/viem#use-another-tempo-id-or-chain) sets the instance.

| Platform | Secure store                                     | Authentication sheet         |
| -------- | ------------------------------------------------ | ---------------------------- |
| iOS      | Keychain                                         | `ASWebAuthenticationSession` |
| Android  | `SharedPreferences`, encrypted with the Keystore | Custom Tab                   |

An app has no page, so only the session's access key sends a payment of <SourceLink name="pay" path="src/Accounts.ts">`accounts.pay`</SourceLink>, through the <SourceLink name="viem" path="src/plugins/viem.ts">`viem`</SourceLink> plugin. Add `viem()` to `plugins` to send payments\: without it, `pay` throws <SourceLink name="PageRequiredError" path="src/actions/account.ts">`Actions.account.PageRequiredError`</SourceLink>, whose message names the missing plugin.

:::note
`accounts` installs `crypto.getRandomValues`, which React Native lacks. If a module imports `viem` or `ox` before `accounts`, import `react-native-get-random-values` first, since their hash library reads `crypto` once as it loads.
:::

### Sign the user in

<SourceLink name="signIn" path="src/plugins/redirect.ts">`redirect.signIn`</SourceLink> opens Tempo ID in the sheet, redeems the callback's code, saves the session, and returns it.

:::code-group
```tsx [SignIn.tsx]
import { Button } from 'react-native'
import { accounts } from './tempo.config.js'

export function SignIn() {
  return (
    <Button
      onPress={async () => {
        const session = await accounts.redirect.signIn() // [!code hl]
        // The user closed the sheet.
        if (!session) return
        console.log(`Signed in as ${session.user.email}`)
      }}
      title="Sign in with Tempo"
    />
  )
}
```

```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { expo } from 'accounts/expo'
import { react } from 'accounts/react'

export const accounts = Accounts.create({
  // Each sign-in requests an access key that sends up to 100 OUSD for a day.
  accessKey: () => ({
    expiry: '1d',
    limits: [{ limit: '100', token: 'ousd' }],
  }),
  chain: 'testnet',
  // The client ID of the app's registration.
  clientId: 'example-mobile',
  plugins: [expo({ redirectUri: 'com.example.app:/callback' }), react()],
})
```
:::

| The user             | <SourceLink name="signIn" path="src/plugins/redirect.ts">`redirect.signIn`</SourceLink>                                             |
| -------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| Approves the request | Returns the session                                                                                                                 |
| Closes the sheet     | Returns `undefined`                                                                                                                 |
| Denies the request   | Throws an <SourceLink name="RequestError" path="src/Accounts.ts">`Accounts.RequestError`</SourceLink> with the code `access_denied` |

If Tempo ID does not know the client ID or the redirect URI, the sheet shows an error page, and no callback returns.

### Render the session

<SourceLink name="useSession" path="src/react/index.ts">`accounts.useSession`</SourceLink> reads the secure store at the first render, with <SourceLink name="isPending" path="src/react/index.ts">`isPending`</SourceLink> until the read ends, so a restart needs no sign-in.

If the read fails, such as while the device is locked, the hook throws the store's error to the nearest error boundary, and the status stays pending. The next mount reads the store again.

:::code-group
```tsx [App.tsx]
import { Button, Text } from 'react-native'
import { accounts } from './tempo.config.js'

export function App() {
  const { isPending, session } = accounts.useSession() // [!code hl]

  if (isPending) return null
  if (!session)
    return (
      <Button
        onPress={() => accounts.redirect.signIn()}
        title="Sign in with Tempo"
      />
    )

  return <Text>Signed in as {session.user.email}</Text>
}
```

```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { expo } from 'accounts/expo'
import { react } from 'accounts/react'

export const accounts = Accounts.create({
  // Each sign-in requests an access key that sends up to 100 OUSD for a day.
  accessKey: () => ({
    expiry: '1d',
    limits: [{ limit: '100', token: 'ousd' }],
  }),
  chain: 'testnet',
  // The client ID of the app's registration.
  clientId: 'example-mobile',
  plugins: [expo({ redirectUri: 'com.example.app:/callback' }), react()],
})
```
:::

The session ends with its [access key](/docs/guides/access-keys). After the access key's <SourceLink name="expiry" path="src/Permissions.ts">`expiry`</SourceLink>, the hook restores no session.

### Sign the user out

<SourceLink name="signOut" path="src/Accounts.ts">`signOut`</SourceLink> empties the session, deletes it from the secure store, and revokes its refresh token. Every other instance in the app on an `expo` preset empties its session at once.

:::code-group
```tsx [SignOut.tsx]
import { Button } from 'react-native'
import { accounts } from './tempo.config.js'

export function SignOut() {
  return <Button onPress={() => accounts.signOut()} title="Sign out" />
}
```

```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { expo } from 'accounts/expo'
import { react } from 'accounts/react'

export const accounts = Accounts.create({
  // Each sign-in requests an access key that sends up to 100 OUSD for a day.
  accessKey: () => ({
    expiry: '1d',
    limits: [{ limit: '100', token: 'ousd' }],
  }),
  chain: 'testnet',
  // The client ID of the app's registration.
  clientId: 'example-mobile',
  plugins: [expo({ redirectUri: 'com.example.app:/callback' }), react()],
})
```
:::

The next sign-in always shows Tempo ID's sign-in page, so another user can sign in. Offline, <SourceLink name="signOut" path="src/Accounts.ts">`signOut`</SourceLink> rejects, but the session stays empty, and the next <SourceLink name="signOut" path="src/Accounts.ts">`signOut`</SourceLink> revokes the refresh token that the secure store keeps.
::::

## Use cases

Each use case sets one option of <SourceLink name="signIn" path="src/plugins/redirect.ts">`redirect.signIn`</SourceLink>, of the <SourceLink name="expo" path="src/plugins/expo.ts">`expo`</SourceLink> preset, or of the <SourceLink name="redirect" path="src/plugins/redirect.ts">`redirect`</SourceLink> plugin.

### Bind a challenge

<SourceLink name="signIn.challenge" path="src/plugins/redirect.ts">`challenge`</SourceLink> has the user sign a server's message at the sign-in. The returned session's <SourceLink name="challengeSignature" path="src/Session.ts">`challengeSignature`</SourceLink> holds the signature, which the server checks, as [Sign challenges](/docs/guides/account-proof/sign-challenges) shows.

:::code-group
```tsx [SignIn.tsx]
import { Button } from 'react-native'
import { accounts } from './tempo.config.js'

export function SignIn() {
  async function signIn() {
    const response = await fetch('https://api.example.com/challenge', {
      method: 'POST',
    })
    // [!code hl:start]
    const session = await accounts.redirect.signIn({
      challenge: await response.text(),
    })
    // [!code hl:end]
    if (!session) return
    await fetch('https://api.example.com/verify', {
      body: JSON.stringify({
        address: session.address,
        signature: session.challengeSignature,
      }),
      headers: { 'content-type': 'application/json' },
      method: 'POST',
    })
  }

  return <Button onPress={signIn} title="Sign in with Tempo" />
}
```

```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { expo } from 'accounts/expo'
import { react } from 'accounts/react'

export const accounts = Accounts.create({
  // Each sign-in requests an access key that sends up to 100 OUSD for a day.
  accessKey: () => ({
    expiry: '1d',
    limits: [{ limit: '100', token: 'ousd' }],
  }),
  chain: 'testnet',
  // The client ID of the app's registration.
  clientId: 'example-mobile',
  plugins: [expo({ redirectUri: 'com.example.app:/callback' }), react()],
})
```
:::

### Ask for funds

<SourceLink name="signIn.funding" path="src/plugins/redirect.ts">`funding`</SourceLink> names the amount that the app needs in the user's Tempo Account. If the account holds less, Tempo ID's deposit page opens in the sheet after the approval.

:::code-group
```tsx [SignIn.tsx]
import { Button } from 'react-native'
import { accounts } from './tempo.config.js'

export function SignIn() {
  return (
    <Button
      onPress={() =>
        accounts.redirect.signIn({
          funding: { amount: '10', currency: 'USD' }, // [!code hl]
        })
      }
      title="Sign in with Tempo"
    />
  )
}
```

```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { expo } from 'accounts/expo'
import { react } from 'accounts/react'

export const accounts = Accounts.create({
  // Each sign-in requests an access key that sends up to 100 OUSD for a day.
  accessKey: () => ({
    expiry: '1d',
    limits: [{ limit: '100', token: 'ousd' }],
  }),
  chain: 'testnet',
  // The client ID of the app's registration.
  clientId: 'example-mobile',
  plugins: [expo({ redirectUri: 'com.example.app:/callback' }), react()],
})
```
:::

### Fill in the email

<SourceLink name="signIn.loginHint" path="src/plugins/redirect.ts">`loginHint`</SourceLink> fills in the email field of Tempo ID's sign-in page, and the user can still change it. It defaults to the saved session's email. A refused refresh ends the session, so the app then passes the email that it kept.

:::code-group
```tsx [SignIn.tsx]
import { Button } from 'react-native'
import { accounts } from './tempo.config.js'

export function SignIn() {
  return (
    <Button
      onPress={() =>
        accounts.redirect.signIn({
          loginHint: 'alice@example.com', // [!code hl]
        })
      }
      title="Sign in with Tempo"
    />
  )
}
```

```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { expo } from 'accounts/expo'
import { react } from 'accounts/react'

export const accounts = Accounts.create({
  // Each sign-in requests an access key that sends up to 100 OUSD for a day.
  accessKey: () => ({
    expiry: '1d',
    limits: [{ limit: '100', token: 'ousd' }],
  }),
  chain: 'testnet',
  // The client ID of the app's registration.
  clientId: 'example-mobile',
  plugins: [expo({ redirectUri: 'com.example.app:/callback' }), react()],
})
```
:::

### Sign in for an API

<SourceLink name="signIn.resource" path="src/plugins/redirect.ts">`resource`</SourceLink> names a [registered resource](https\://github.com/tempoxyz/id/blob/main/docs/resources.md), such as an MCP server. Each access token then names it as its audience, so only that API accepts the token.

:::code-group
```tsx [SignIn.tsx]
import { Button } from 'react-native'
import { accounts } from './tempo.config.js'

export function SignIn() {
  return (
    <Button
      onPress={() =>
        accounts.redirect.signIn({
          resource: 'https://mcp.example.com/mcp', // [!code hl]
        })
      }
      title="Sign in with Tempo"
    />
  )
}
```

```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { expo } from 'accounts/expo'
import { react } from 'accounts/react'

export const accounts = Accounts.create({
  // Each sign-in requests an access key that sends up to 100 OUSD for a day.
  accessKey: () => ({
    expiry: '1d',
    limits: [{ limit: '100', token: 'ousd' }],
  }),
  chain: 'testnet',
  // The client ID of the app's registration.
  clientId: 'example-mobile',
  plugins: [expo({ redirectUri: 'com.example.app:/callback' }), react()],
})
```
:::

### Share the browser's Tempo ID session

On iOS, the sheet shares no cookies with the system browser, so each sign-in shows Tempo ID's sign-in page. With <SourceLink name="ephemeral" path="src/plugins/expo.ts">`ephemeral`</SourceLink> set to `false`, it shares them, and a user signed in to Tempo ID there only approves the request.

```ts [tempo.config.ts]
import { Accounts } from 'accounts'
import { expo } from 'accounts/expo'
import { react } from 'accounts/react'

export const accounts = Accounts.create({
  // Each sign-in requests an access key that sends up to 100 OUSD for a day.
  accessKey: () => ({
    expiry: '1d',
    limits: [{ limit: '100', token: 'ousd' }],
  }),
  chain: 'testnet',
  // The client ID of the app's registration.
  clientId: 'example-mobile',
  plugins: [
    expo({ ephemeral: false, redirectUri: 'com.example.app:/callback' }), // [!code hl]
    react(),
  ],
})
```

On Android, the sheet always shares them, so the option has no effect.

### Sign in without Expo

An app without Expo passes <SourceLink name="redirect" path="src/plugins/redirect.ts">`redirect`</SourceLink> with its own <SourceLink name="open" path="src/plugins/redirect.ts">`open`</SourceLink>, and its own <SourceLink name="create.store" path="src/Accounts.ts">`store`</SourceLink>. `native.ts` stands for the app's native modules.

:::code-group
```ts [tempo.config.ts]
import { Accounts, Store } from 'accounts'
import { redirect } from 'accounts/plugins'
import { keychain, openAuthSession } from './native.js'

export const accounts = Accounts.create({
  chain: 'testnet',
  clientId: 'example-mobile',
  plugins: [
    redirect({
      open: (url, options) => openAuthSession(url, options.redirectUri),
    }),
  ],
  redirectUri: 'com.example.app:/callback',
  store: Store.from(keychain),
})
```

```ts [native.ts]
import type { Store } from 'accounts'

// Each declaration stands for a native module of the app.
export declare const keychain: Store.Store

export declare function openAuthSession(
  url: string,
  redirectUri: string,
): Promise<string | undefined>
```
:::

| Module            | Contract                                                                                                          |
| ----------------- | ----------------------------------------------------------------------------------------------------------------- |
| `keychain`        | Returns each value as it was set, a `bigint` included. A store of strings serializes with ox's `Json`.            |
| `openAuthSession` | Shows the URL, closes at the redirect URI, and resolves with the callback URL, or `undefined` for a closed sheet. |

The app also installs `react-native-get-random-values`, since React Native links only the native modules of the app's own `package.json`.

## Next steps

<PageCard description="Read the session in components, with a hook." icon="react" title="React" to="/docs/guides/react/manage-sessions" />

<PageCard description="Name what an access key may spend, and request it at sign-in or later." icon="key" title="Authorize access keys" to="/docs/guides/access-keys/authorize-access-keys" />

<PageCard description="Send transactions and sign messages with the access key." icon="viem" title="Viem" to="/docs/guides/viem" />

<PageCard description="End the session of the app, or of every app." icon="log-out" title="Sign-out" to="/docs/guides/sign-out/end-app-sessions" />
