@authon/react-native
v0.9.6
Published
Authon React Native SDK — mobile authentication
Maintainers
Readme
English | 한국어
@authon/react-native
Drop-in React Native authentication with secure token storage — Auth0 alternative
Prerequisites
Before installing the SDK, create an Authon project and get your API keys:
Create a project at Authon Dashboard
- Click "Create Project" and enter your app name
- Select the authentication methods you want (Email/Password, OAuth providers, etc.)
Get your API keys from Project Settings → API Keys
- Publishable Key (
pk_live_...) — use in your frontend code - Test Key (
pk_test_...) — for development, enables Dev Teleport
- Publishable Key (
Configure OAuth providers (optional) in Project Settings → OAuth
- Add Google, Apple, GitHub, etc. with their respective Client ID and Secret
- Set the redirect URL to
https://api.authon.dev/v1/auth/oauth/redirect
Test vs Live keys: Use
pk_test_...during development. Switch topk_live_...before deploying to production. Test keys use a sandbox environment with no rate limits.
Install
npm install @authon/react-native react-native-svg
npx expo install expo-secure-store expo-web-browserQuick Start
// App.tsx — complete working file
import React, { useState } from 'react';
import { View, Text, Button, TextInput, ActivityIndicator } from 'react-native';
import { AuthonProvider, useAuthon, useUser } from '@authon/react-native';
import * as SecureStore from 'expo-secure-store';
const storage = {
getItem: (key: string) => SecureStore.getItemAsync(key),
setItem: (key: string, value: string) => SecureStore.setItemAsync(key, value),
removeItem: (key: string) => SecureStore.deleteItemAsync(key),
};
function HomeScreen() {
const { isLoaded, isSignedIn, user, signIn, signOut } = useAuthon();
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
if (!isLoaded) return <ActivityIndicator />;
if (isSignedIn) {
return (
<View style={{ padding: 24 }}>
<Text>Welcome, {user?.displayName ?? user?.email}</Text>
<Button title="Sign Out" onPress={signOut} />
</View>
);
}
return (
<View style={{ padding: 24, gap: 12 }}>
<TextInput placeholder="Email" value={email} onChangeText={setEmail} autoCapitalize="none" />
<TextInput placeholder="Password" value={password} onChangeText={setPassword} secureTextEntry />
<Button title="Sign In" onPress={() => signIn({ strategy: 'email_password', email, password })} />
</View>
);
}
export default function App() {
return (
<AuthonProvider
publishableKey="pk_live_YOUR_PUBLISHABLE_KEY"
storage={storage}
>
<HomeScreen />
</AuthonProvider>
);
}Common Tasks
Add Google OAuth Login
import * as WebBrowser from 'expo-web-browser';
import { useAuthon } from '@authon/react-native';
// 1. Add your app scheme (e.g. "myapp://") to the project's allowed origins in the dashboard.
// 2. Optionally set <AuthonProvider oauthReturnTo="myapp://oauth-callback" ...> so
// startOAuth() and <SocialButtons /> know where to return.
function GoogleButton() {
const { startOAuth, completeOAuth } = useAuthon();
const handlePress = async () => {
const { url } = await startOAuth('google', { returnTo: 'myapp://oauth-callback' });
const result = await WebBrowser.openAuthSessionAsync(url, 'myapp://oauth-callback');
if (result.type === 'success') await completeOAuth(result.url);
};
return <Button title="Sign in with Google" onPress={handlePress} />;
}From 0.9.1, OAuth uses PKCE:
startOAuthkeeps a verifier in the client and sends only its hash.- Authon redirects to
returnTowith a one-timeauthon_code. completeOAuth(callbackUrl)exchanges that code with the verifier.GET /v1/auth/oauth/pollreturns status only, socompleteOAuth(state)on its own can no longer get tokens. It now waits untilhandleOAuthCallback(url)receives the deep link.crypto.getRandomValuesis required (Expo SDK 49+ orreact-native-get-random-values).- If the user has MFA enabled,
completeOAuth/handleOAuthCallbackreject withAuthonMfaRequiredError(and emitmfaRequired). No session exists yet; finish withverifyMfa(error.mfaToken, code):
import { AuthonMfaRequiredError, useAuthon } from '@authon/react-native';
const { completeOAuth, verifyMfa } = useAuthon();
try {
await completeOAuth(result.url);
} catch (err) {
if (err instanceof AuthonMfaRequiredError) {
const code = await askUserForTotpCode();
await verifyMfa(err.mfaToken, code);
} else throw err;
}Add Google OAuth (Expo recommended)
import * as WebBrowser from 'expo-web-browser';
import { useAuthon } from '@authon/react-native';
function GoogleButton() {
const { startOAuth, completeOAuth } = useAuthon();
const handlePress = async () => {
// https bridge on an allowed origin that 302-redirects to
// myapp://oauth-callback, forwarding authon_code and authon_oauth_state.
const { url } = await startOAuth('google', {
returnTo: 'https://your-domain.com/mobile-callback',
});
const result = await WebBrowser.openAuthSessionAsync(url, 'myapp://oauth-callback');
if (result.type === 'success') await completeOAuth(result.url);
};
return <Button title="Sign in with Google" onPress={handlePress} />;
}Get Current User
import { useUser } from '@authon/react-native';
function Profile() {
const { isLoaded, isSignedIn, user } = useUser();
if (!isLoaded) return <ActivityIndicator />;
if (!isSignedIn) return <Text>Not signed in</Text>;
return <Text>Email: {user?.email}</Text>;
}Add Email/Password Auth
const { signIn } = useAuthon();
await signIn({ strategy: 'email_password', email: '[email protected]', password: 'MyP@ssw0rd' });Email sign-in when the project requires CAPTCHA
If the project turned on CAPTCHA, the server rejects email sign-in and sign-up without a Cloudflare Turnstile token (CAPTCHA_REQUIRED). Install react-native-webview and render AuthonTurnstile above the form. It reads the site key from the project and renders nothing when the project does not require CAPTCHA. Set captchaHost to the project domain the widget is registered for (Cloudflare only issues tokens for that host).
import { WebView } from 'react-native-webview';
import { AuthonProvider, AuthonTurnstile, useAuthon, type AuthonTurnstileHandle } from '@authon/react-native';
<AuthonProvider publishableKey="pk_live_..." captchaHost="example.com">...</AuthonProvider>
function EmailForm() {
const { signIn } = useAuthon();
const captcha = useRef<AuthonTurnstileHandle>(null);
const [token, setToken] = useState<string>();
async function submit() {
try {
await signIn({ strategy: 'email_password', email, password, turnstileToken: token });
} catch (e) {
// A token works once: get a new one after any failed attempt.
setToken(undefined);
captcha.current?.reset();
throw e;
}
}
return (
<>
<AuthonTurnstile ref={captcha} webView={WebView} onToken={setToken} onExpire={() => setToken(undefined)} />
{/* email, password, and a button that calls submit() */}
</>
);
}If the widget cannot run (Cloudflare unreachable, the WebView process crashed twice after automatic retries, or the script did not load within 20 seconds), onError receives CAPTCHA_UNAVAILABLE. Pass inspectable to debug the widget with Safari Web Inspector or Chrome DevTools.
client.getCaptchaConfig() returns { required, siteKey, host } if you build your own form logic. signUp takes turnstileToken the same way. Error codes: CAPTCHA_REQUIRED, CAPTCHA_FAILED (token expired or reused; retry with a new one), CAPTCHA_UNAVAILABLE (widget or Cloudflare unreachable; retry).
Handle Sign Out
const { signOut } = useAuthon();
await signOut();Errors
Sign-in failures are AuthonAuthError (an Error) with code, message, diagnosticId and
retryable. diagnosticId is the server's request ID (requestId in the error body or the
X-Request-Id header) when a response arrived; log it (never tokens, codes or callback URLs) and
quote it when contacting support. The codes are the same in the Swift, Kotlin and React Native SDKs.
| Code | When | Retryable | Session | What the app should do |
|---|---|---|---|---|
| OAUTH_CANCELLED | The user closed the browser / auth session | no | unchanged | Not an error: go back quietly |
| OAUTH_START_FAILED | The sign-in URL could not be issued | yes | unchanged | Offer to retry |
| OAUTH_REDIRECT_NOT_ALLOWED | returnTo missing or not registered, PKCE missing | no | unchanged | Developer setup: check allowed origins / app registration |
| OAUTH_PROVIDER_ERROR | The provider came back with an error (denied, ...) | yes | unchanged | Retry with the same provider |
| OAUTH_STATE_MISMATCH | A callback for a sign-in this app is not running | yes | unchanged | Start over |
| OAUTH_EXCHANGE_FAILED | The one-time code expired or was reused | yes | unchanged | Start over |
| OAUTH_TIMEOUT | completeOAuth(state) got no callback in 3 minutes | yes | unchanged | Start over |
| ACCOUNT_LINK_REQUIRED | The email belongs to an account of another provider (explicit linking project) | no | unchanged | Ask the user to sign in with the original method |
| MFA_REQUIRED | Second factor needed (AuthonMfaRequiredError, has mfaToken) | — | none yet | Show the code screen, then verifyMfa |
| INVALID_CREDENTIALS | Wrong email or password | no | unchanged | Check the input |
| SESSION_EXPIRED | The refresh token was rejected (emitted on error, then signedOut) | no | cleared | Sign in again |
| NOT_SIGNED_IN | A call that needs a session was made with none | no | none | Show sign-in |
| NETWORK_ERROR | No response | yes | kept | Check the connection and retry |
| RATE_LIMITED | HTTP 429 | yes (later) | kept | Retry after a pause |
| API_ERROR | Any other server error | yes | kept | Retry; contact support with diagnosticId |
Handling the browser step (expo-web-browser is not a dependency; any { type, url } result works):
import * as WebBrowser from 'expo-web-browser';
import { AuthonAuthError, AuthonMfaRequiredError, useAuthon } from '@authon/react-native';
const { startOAuth, client } = useAuthon();
const { url, state } = await startOAuth('google', { returnTo: 'myapp://oauth-callback' });
const result = await WebBrowser.openAuthSessionAsync(url, 'myapp://oauth-callback');
try {
// Success: finishes the sign-in. cancel / dismiss: ends the flow and throws OAUTH_CANCELLED.
await client.completeOAuthFromAuthSession(state, result);
} catch (err) {
if (err instanceof AuthonAuthError && err.code === 'OAUTH_CANCELLED') return;
if (err instanceof AuthonMfaRequiredError) return showMfaScreen(err.mfaToken);
showError(err instanceof AuthonAuthError ? err : null);
}callbackUrlFromAuthSession(result) returns the callback URL (or throws OAUTH_CANCELLED) if you
call completeOAuth(url) yourself; client.cancelOAuth(state) ends a flow you abandon.
Native Sign in with Apple (iOS)
signInWithAppleNative(client) from @authon/react-native-wallet shows the system Apple sheet and hands
the result to client.adoptSignInResult(result), which makes it the session exactly like a finished
OAuth sign-in (AuthonProvider state updates through the signedIn event; MFA throws
AuthonMfaRequiredError). See that package's README.
Environment Variables
| Variable | Required | Description |
|----------|----------|-------------|
| AUTHON_PUBLISHABLE_KEY | Yes | Project publishable key (pk_live_... or pk_test_...) |
| AUTHON_API_URL | No | Optional — defaults to api.authon.dev |
API Reference
Components
| Component | Description |
|-----------|-------------|
| <AuthonProvider> | Provider with publishableKey, apiUrl, storage |
| <SocialButtons> | Renders all enabled OAuth provider buttons |
| <SocialButton> | Single OAuth provider button with icon |
| <AuthonTurnstile> | Cloudflare Turnstile for projects that require CAPTCHA (needs react-native-webview) |
Hooks
| Hook | Returns |
|------|---------|
| useAuthon() | { isLoaded, isSignedIn, user, signIn, signUp, signOut, getToken, providers, branding, startOAuth, completeOAuth, handleOAuthCallback, verifyMfa, on, client } |
| useUser() | { isLoaded, isSignedIn, user } |
| useAuthonWeb3() | Web3 wallet auth |
| useAuthonPasswordless() | OTP and magic link |
| useAuthonPasskeys() | Passkey registration and auth |
Comparison
| Feature | Authon | Clerk | Auth0 | |---------|--------|-------|-------| | Pricing | Free | $25/mo+ | $23/mo+ | | React Native | Yes | Yes | Yes | | Secure token storage | Yes | Yes | Yes | | Web3 auth | Yes | No | No | | MFA/Passkeys | Yes | Yes | Yes |
License
MIT
Delete the signed-in account
This requires the self-account-deletion API rollout; it is not supported by older servers. Show an irreversible deletion confirmation, including the loss of server-held embedded wallet shares and backups. Transfer assets or establish independent access first. Authon does not move assets or remove blockchain records. Do not automatically create a replacement wallet after deletion.
const { deleteAccount } = useAuthon();
// After the user explicitly confirms and the app arranges its own backend-data deletion:
const result = await deleteAccount({ confirm: true });
// Authon auth state is now signed out. Also erase the app's native wallet and local app data.
if (!result.localSessionCleared) {
// Server deletion is complete; retry clearing the app-provided secure token storage.
}
if (result.appleRevocation === 'manual') {
// Present Apple's manual Sign in with Apple authorization-removal instructions.
}The same method is available as client.deleteAccount(options). It uses the current user's
access token and publishable key; never a project secret. The server requires authentication within
five minutes, measured from the original session in a refresh family. REAUTH_REQUIRED means
sign in again (including MFA when required); refresh alone is insufficient. Existing sign-in flows
remain supported; old/sid-less sessions must sign in again only for this operation.
APPLE_REAUTH_REQUIRED means an older Apple account has no usable stored revocation token.
Prefer signing in with Apple again, then retry. If that cannot be done, first explain Apple's
manual revocation procedure and, only after the user accepts it, call
deleteAccount({ confirm: true, appleRevocationFallback: 'manual' }). The result explicitly reports
appleRevocation: 'manual'; it does not claim Apple's authorization was revoked. This exception
covers missing legacy grants, not configured-token revocation failures.
APPLE_REVOCATION_UNAVAILABLE leaves Authon data intact: retry later or have the project operator
repair Apple credentials. A network error can mean the response was lost after deletion committed;
do not report success, recreate a wallet, or initiate another sign-in automatically. Reconcile with
the app's account-deletion status and support using the request ID, never tokens. A successful
server deletion followed by a secure-storage failure returns localSessionCleared: false with
success: true, so app-owned wallet cleanup can still proceed.
Authon emits the existing user.deleted webhook after committing. Apps with their own backend
must implement idempotent deletion there; webhook delivery can fail. Audit/webhook records and
disaster-recovery backups follow operator retention policies, not an invented 30-day cancellation
window. Re-registering later creates a new account and does not recover the deleted wallet.
