Skip to content
Agentpost robot in sunglasses on a red circleAgentpost

Native apps

An Expo or React Native app signs principals in with the same workflows as a web app, through @agentpost-tools/identityhound-react, whose hooks render nothing and touch no DOM. What differs on a phone is the key the app holds, where the session is kept, and how a provider’s page opens and returns to the app. This page covers those three; Clients has the identity’s methods, and Session strategies the strategies.

Use a React Native or Expo app with React 19.

npx expo install expo-secure-store expo-web-browser expo-linking
npm i @agentpost-tools/identityhound-react @agentpost-tools/identityhound-sdk

The key and the return address

A native app sends no Origin header, so it holds a publishable key issued with allowNativeApps: true, one for each platform, such as ios and android. Native apps says how to issue one, what it reaches, and what it doesn’t protect against.

A sign-in with a provider ends at a return address in the config’s urls.oauthReturn. For a native app, that is an https app link: a universal link on iOS and an App Link on Android, such as https://app.example.com/oauth/return, on a domain whose apple-app-site-association and assetlinks.json name your app. The platform uses that association to open your app for that address. A private-use scheme, such as com.example.app:/oauth, is refused: any app may claim the same scheme, and the code and state on the return address are enough to finish the sign-in with your public key.

Keep the session in the keychain

deviceSession keeps the principal’s session in the storage you pass. Wrap expo-secure-store, which keeps it in the iOS keychain and Android’s Keystore, so the principal stays signed in across launches:

// keychain.ts
import * as SecureStore from 'expo-secure-store';
import type { KeyValueStorage } from '@agentpost-tools/identityhound-sdk/workflows';

export const keychain: KeyValueStorage = {
  getItem: (key) => SecureStore.getItemAsync(key),
  setItem: (key, value) => SecureStore.setItemAsync(key, value),
  removeItem: (key) => SecureStore.deleteItemAsync(key),
};

Pass it to the provider as the session’s storage, and as the identity’s storage, which keeps a provider sign-in in progress if the app is closed while the provider’s page is open:

// App.tsx
import { IdentityhoundProvider } from '@agentpost-tools/identityhound-react';
import { deviceSession } from '@agentpost-tools/identityhound-sdk/workflows';
import { keychain } from './keychain';
import { SignIn } from './SignIn';

const publishableKey = process.env.EXPO_PUBLIC_AGENTPOST_PUBLISHABLE_KEY!;

export default function App() {
  return (
    <IdentityhoundProvider
      publishableKey={publishableKey}
      session={deviceSession({ storage: keychain })}
      storage={keychain}
    >
      <SignIn />
    </IdentityhoundProvider>
  );
}

On launch the provider asks IdentityHound who the stored session signs in, with GET /me. If the session is still active, useSession() becomes signed_in without another sign-in. With the strategy above, signed-in calls send a short-lived user token, minted from the session when the first call needs one.

Sign in with an emailed code

The quickest way is IdentityHound’s finished sign-in screen: a file you copy into your app and restyle, over parts from @agentpost-tools/identityhound-ui/native that handle the steps, code autofill, the resend wait, the errors, and the screen reader. Email sign-in for React Native shows how to add it.

For a screen entirely your own, useEmailCodeSignIn() runs the email step and the code step. Its state says which step to show, the error to show, and resendIn:

// SignIn.tsx
import { useState } from 'react';
import { Button, Text, TextInput, View } from 'react-native';
import {
  useEmailCodeSignIn,
  useSession,
} from '@agentpost-tools/identityhound-react';
import { errorWords } from './errorWords';
import { ProviderSignIn } from './ProviderSignIn';

export function SignIn() {
  const session = useSession();
  const signIn = useEmailCodeSignIn();
  const [value, setValue] = useState('');

  if (session.status === 'signed_in')
    return (
      <View>
        <Text>
          {session.principal.displayName
            ? `Signed in as ${session.principal.displayName}`
            : 'Signed in'}
        </Text>
        <Button title="Sign out" onPress={() => void session.signOut()} />
      </View>
    );
  return (
    <View>
      <TextInput
        value={value}
        onChangeText={setValue}
        autoCapitalize="none"
        placeholder={signIn.step === 'email' ? 'Email' : 'Code'}
      />
      <Button
        title={signIn.step === 'email' ? 'Email me a code' : 'Sign in'}
        disabled={signIn.pending}
        onPress={() => {
          if (signIn.step === 'email') void signIn.requestCode(value);
          else void signIn.verifyCode(value);
          setValue('');
        }}
      />
      {signIn.error ? <Text>{errorWords(signIn.error)}</Text> : null}
      <ProviderSignIn />
    </View>
  );
}

An emailed sign-in link works too, when urls.signInLink is an https app link: read code from the link that opens the app, and pass it to verifyCode. The check needs the request this app made, which the workflow holds in memory. For a link opened on another device, or after the app was closed, the hook reports no_code_sent: request a new code in the app, and use the code from the new email.

Sign in with a provider

useOAuthSignIn({ returnTo }) starts a sign-in with a configured provider, such as twitch, and gives the provider’s page. Open it in the system browser with expo-web-browser, then pass the address the provider returned to into complete. The iOS example uses HTTPS callbacks on iOS 17.4 or later with Associated Domains. Use an Expo WebBrowser version that supports preferUniversalLinks.

// ProviderSignIn.tsx
import { useEffect } from 'react';
import { Button, Text, View } from 'react-native';
import * as Linking from 'expo-linking';
import * as WebBrowser from 'expo-web-browser';
import { useOAuthSignIn } from '@agentpost-tools/identityhound-react';
import { errorWords } from './errorWords';

/** Your https app link, listed in the config's urls.oauthReturn. */
const returnTo = 'https://app.example.com/oauth/return';

export function ProviderSignIn() {
  const oauth = useOAuthSignIn({ returnTo });
  const { complete } = oauth;
  // When the app link opens the app rather than the browser session, the address arrives here.
  const opened = Linking.useURL();
  useEffect(() => {
    if (opened?.startsWith(`${returnTo}?`)) void complete(opened);
  }, [opened, complete]);

  async function signInWithTwitch() {
    const authorizeUrl = await oauth.start('twitch');
    if (!authorizeUrl) return;
    const result = await WebBrowser.openAuthSessionAsync(
      authorizeUrl,
      returnTo,
      { preferUniversalLinks: true },
    );
    if (result.type === 'success') await oauth.complete(result.url);
  }

  return (
    <View>
      <Button
        title="Sign in with Twitch"
        disabled={oauth.status === 'starting' || oauth.status === 'completing'}
        onPress={() => void signInWithTwitch()}
      />
      {oauth.error ? <Text>{errorWords(oauth.error)}</Text> : null}
    </View>
  );
}

complete calls with the same OAuth state on one identity share one result, so both paths can pass the callback. The first completion of a callback with a code must match the saved state, or the hook reports oauth_state_mismatch. When the provider’s page is closed, openAuthSessionAsync returns cancel or dismiss, and start begins again.

Your own API

When your app has its own API, which takes the session as its bearer and decides who may use the app, send the session itself and let your API do the checking:

// App.tsx
import { IdentityhoundProvider } from '@agentpost-tools/identityhound-react';
import { deviceSession } from '@agentpost-tools/identityhound-sdk/workflows';
import { keychain } from './keychain';
import { Home } from './Home';

const publishableKey = process.env.EXPO_PUBLIC_AGENTPOST_PUBLISHABLE_KEY!;
const API = 'https://api.example.com';

const session = deviceSession({
  storage: keychain,
  bearer: 'session',
  // Turn away a principal your API refuses, before the session is stored.
  authorize: async ({ bearer }) => {
    const response = await fetch(`${API}/v1/me`, {
      headers: { authorization: `Bearer ${bearer}` },
    });
    if (response.status === 401 || response.status === 403) return false;
    if (!response.ok) throw new Error(`the API answered ${response.status}`);
    return true;
  },
});

export default function App() {
  return (
    <IdentityhoundProvider
      publishableKey={publishableKey}
      session={session}
      storage={keychain}
      // Your API checks the session on its first call, so ask IdentityHound nothing on launch.
      load={{ verify: false }}
    >
      <Home />
    </IdentityhoundProvider>
  );
}
  • Send the session: useSession().getSessionToken(), or identity.getSessionToken() outside React, returns the session token from the keychain, with no request, or null when nobody is signed in. To read it outside React, such as in your API client, make the identity with createIdentity and pass it to the provider as identity.
  • A refused sign-in: when authorize resolves false, the session is revoked, nothing is stored, and the sign-in’s error is not_authorized.
  • A session your API refuses later: call signOut({ revoke: false }). It forgets the session on this device and sends nothing.
  • Signing out: end the session at your API first if it keeps something per device, such as a push token, with the session from getSessionToken(). Then call signOut(), which deletes the stored session and revokes it with IdentityHound, ignoring a revoke that fails. Sign out has the details.

Errors

Each hook’s error holds a code, typed details for some codes, and a message. The message is for your logs and your agents, not the screen: show words you pick by code, as the email sign-in component does. Its words for each email-code error are emailCodeErrorMessage(error, { step, guessesLeft }) from @agentpost-tools/identityhound-sdk/workflows, if you want them as they are. IdentityHound’s codes are on IdentityHound’s errors page, and the Platform’s on the Platform errors page.

// errorWords.ts
import type {
  EmailCodeError,
  OAuthError,
} from '@agentpost-tools/identityhound-sdk/workflows';

export function errorWords(error: EmailCodeError | OAuthError): string {
  switch (error.code) {
    case 'email_required':
      return 'Enter your email address.';
    case 'code_required':
      return 'Enter the 6-digit code from the email.';
    case 'code_invalid': {
      const left = error.details?.guessesLeft;
      if (left === 0) return 'Too many wrong tries. Send a new code.';
      return left === undefined
        ? 'That code is wrong. Check it and try again.'
        : `That code is wrong. ${left} ${left === 1 ? 'try' : 'tries'} left.`;
    }
    case 'code_expired':
      return 'That code expired. Send a new one.';
    case 'resend_too_soon':
      return 'Wait a moment before sending a new code.';
    case 'throttled':
      return error.details
        ? `Too many tries. Try again in ${Math.ceil(error.details.retryAfter)} seconds.`
        : 'Too many tries. Wait a moment and try again.';
    case 'sign_up_closed':
      return 'That email has no account here.';
    case 'not_authorized':
      return "This account doesn't have access to this app.";
    case 'oauth_cancelled':
      return 'Sign-in was cancelled.';
    case 'session_not_saved':
      return "We couldn't keep you signed in on this device. Try again.";
    case 'network_error':
      return "We couldn't reach the sign-in service. Check your connection.";
    default:
      return 'Something went wrong. Try again.';
  }
}

While resendIn is above 0, after a code was sent or after a throttled answer, disable the button that sends a code and show the countdown.

Two codes are particular to a phone:

  • origin_not_allowed means the key doesn’t allow native apps. Set allowNativeApps: true on it with Update a publishable key.
  • session_not_saved means the sign-in worked but storage couldn’t keep the session, such as when the keychain is locked. The SDK asks IdentityHound to end that session. The principal signs in again when storage is available.