Expo Integration
Integrate Entro Auth with Expo.
Expo is a popular framework for building cross-platform apps with React Native. Entro Auth supports both Expo native and web apps.
@entro314labs/entro-auth-expo is developed and tested against Expo SDK 58 (React Native 0.88). Its peer ranges are wider, so it installs in an older project: expo-constants >=17, expo-linking >=7, expo-network >=8.0.7, expo-secure-store >=12.5 and expo-web-browser >=14. An SDK older than 58 is not tested here.
Installation
Configure A Entro Auth Backend
Before using Entro Auth with Expo, make sure you have a Entro Auth backend set up. You can either use a separate server or leverage Expo's new API Routes feature to host your Entro Auth instance.
To get started, check out our installation guide for setting up Entro Auth on your server. If you prefer, check out the full example.
To use the new API routes feature in Expo to host your Entro Auth instance you can create a new API route in your Expo app and mount the Entro Auth handler.
import { auth } from "@/lib/auth"; // import Entro Auth handler
const handler = auth.handler;
export { handler as GET, handler as POST }; // export handler for both GET and POST requestsInstall Server Dependencies
Install both the Entro Auth package and Expo plugin into your server application.
npm install @entro314labs/entro-auth @entro314labs/entro-auth-expoIf you're using Expo's API Routes, you can follow the step below instead.
Install Client Dependencies
- You also need to install both the Entro Auth package and Expo plugin into your Expo application.
npm install @entro314labs/entro-auth @entro314labs/entro-auth-expo- And you need to install
expo-networkfor network state detection.
npm install expo-network- (Optional) If you're using the default Expo template, these dependencies are already included, so you can skip this step. Otherwise, if you plan to use our social providers (e.g. Google, Apple), your Expo app requires a few additional dependencies.
npm install expo-linking expo-web-browser expo-constants
Add the Expo Plugin on Your Server
Add the Expo plugin to your Entro Auth server.
import { entroAuth } from "@entro314labs/entro-auth";
import { expo } from "@entro314labs/entro-auth-expo";
export const auth = entroAuth({
plugins: [expo()],
emailAndPassword: {
enabled: true, // Enable authentication using email and password.
},
});Initialize Entro Auth Client
To initialize Entro Auth in your Expo app, you need to call createAuthClient with the base URL of your Entro Auth backend. Make sure to import the client from /react.
Make sure you install the expo-secure-store package into your Expo app. This is used to store the session data and cookies securely.
npm install expo-secure-storeYou need to also import client plugin from @entro314labs/entro-auth-expo/client and pass it to the plugins array when initializing the auth client.
This is important because:
- Social Authentication Support: enables social auth flows by handling authorization URLs and callbacks within the Expo web browser.
- Secure Cookie Management: stores cookies securely and automatically adds them to the headers of your auth requests.
import { createAuthClient } from "@entro314labs/entro-auth/react";
import { expoClient } from "@entro314labs/entro-auth-expo/client";
import * as SecureStore from "expo-secure-store";
export const authClient = createAuthClient({
baseURL: "http://localhost:8081", // Base URL of your Entro Auth backend.
plugins: [
expoClient({
scheme: "myapp",
storagePrefix: "myapp",
storage: SecureStore,
})
]
});Be sure to include the full URL, including the path, if you've changed the default path from /api/auth.
Scheme and Trusted Origins
Entro Auth uses deep links to redirect users back to your app after authentication. To enable this, you need to add your app's scheme to the trustedOrigins list in your Entro Auth config.
First, make sure you have a scheme defined in your app.json file.
{
"expo": {
"scheme": "myapp"
}
}Then, update your Entro Auth config to include the scheme in the trustedOrigins list.
export const auth = entroAuth({
trustedOrigins: ["myapp://"]
})If you have multiple schemes or need to support deep linking with various paths, you can use specific patterns or wildcards:
export const auth = entroAuth({
trustedOrigins: [
// Basic scheme
"myapp://",
// Production & staging schemes
"myapp-prod://",
"myapp-staging://",
// Wildcard support for all paths following the scheme
"myapp://*"
]
})Development Mode
During development, Expo uses the exp:// scheme with your device's local IP address. To support this, you can use wildcards to match common local IP ranges:
export const auth = entroAuth({
trustedOrigins: [
"myapp://",
// Development mode - Expo's exp:// scheme with local IP ranges
...(process.env.NODE_ENV === "development" ? [
"exp://", // Trust any host of the exp:// scheme
"exp://**", // Trust all Expo URLs (wildcard matching)
"exp://192.168.*.*:*/**", // Trust 192.168.x.x IP range with any port and path
] : [])
]
})For more information about trusted origins, see the trusted origins documentation.
The wildcard patterns for exp:// should only be used in development. In production, use your app's specific scheme (e.g., myapp://).
The authorization proxy only redirects to the authorization endpoint of a configured social or generic OAuth provider, or of an SSO provider on a trusted origin. To sign in through an SSO identity provider, add its origin to trustedOrigins.
Configure Metro Bundler
Entro Auth relies on package.json exports to resolve its modules. Starting with Expo SDK 53, package exports support is enabled by default in Metro, so no extra Metro configuration is needed.
If you have a custom metro.config.js, make sure you're not disabling package exports:
const { getDefaultConfig } = require("expo/metro-config");
const config = getDefaultConfig(__dirname);
// Do NOT set this to false — Entro Auth requires package exports
// config.resolver.unstable_enablePackageExports = false;
module.exports = config;Don't forget to clear the cache after making changes to your Metro config.
npx expo start --clearUsage
Authenticating Users
With Entro Auth initialized, you can now use the authClient to authenticate users in your Expo app.
import { useState } from "react";
import { View, TextInput, Button } from "react-native";
import { authClient } from "@/lib/auth-client";
export default function SignIn() {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const handleLogin = async () => {
await authClient.signIn.email({
email,
password,
})
};
return (
<View>
<TextInput
placeholder="Email"
value={email}
onChangeText={setEmail}
/>
<TextInput
placeholder="Password"
value={password}
onChangeText={setPassword}
/>
<Button title="Login" onPress={handleLogin} />
</View>
);
}Social Sign-In
For social sign-in, you can use the authClient.signIn.social method with the provider name and a callback URL. When you pass a relative path like "/dashboard", the Expo plugin automatically converts it to a deep link using Linking.createURL.
When upgrading your auth backend to purpose-prefixed verification identifiers or purpose-specific state-cookie keys, restart pending redirect-based social sign-ins. Follow the verification storage and state-cookie cutover guidance. These format changes do not require new Expo client configuration and do not affect native ID-token sign-in, which does not use redirect state.
import { Button } from "react-native";
import { router } from "expo-router";
import { authClient } from "@/lib/auth-client";
export default function SocialSignIn() {
const handleLogin = async () => {
const { error } = await authClient.signIn.social({
provider: "google",
callbackURL: "/dashboard"
})
if (error) {
// handle error
return;
}
router.replace("/dashboard");
};
return <Button title="Login with Google" onPress={handleLogin} />;
}On native (iOS/Android), signIn.social does not navigate automatically. Handle navigation yourself after it resolves. Note that the underlying browser behavior differs by platform.
When the account has two-factor on, the sign-in is held back for the second step. signIn.social then resolves with twoFactorRedirect: true and twoFactorMethods in its data, as a password sign-in does; show the code screen and call twoFactor.verifyTotp (or the method the account uses):
const { data, error } = await authClient.signIn.social({
provider: "google",
callbackURL: "/dashboard",
});
if (data?.twoFactorRedirect) {
router.push("/two-factor");
}When the server refuses the sign-in after the provider's page, it sends the browser to errorCallbackURL with the reason in error. Name an address of the app there, the same as callbackURL or under it, and signIn.social and linkSocial resolve with that reason as error in their data, and errorDescription when the server gave one:
const { data } = await authClient.signIn.social({
provider: "google",
callbackURL: "/dashboard",
errorCallbackURL: "/dashboard",
});
if (data?.error === "PROVIDER_NOT_LINKED") {
// the account has two-factor on, and this provider is not linked to it yet
}Without an errorCallbackURL of the app's, the refusal lands on the server's own error page in the system browser, and the app only learns that no session came back.
IdToken Sign-In
If you want to make provider request on the mobile device and then verify the ID token on the server, you can use the authClient.signIn.social method with the idToken option.
import { Button } from "react-native";
export default function SocialSignIn() {
const handleLogin = async () => {
await authClient.signIn.social({
provider: "google", // only google, apple and facebook are supported for idToken signIn
idToken: {
token: "...", // ID token from provider
nonce: "...", // nonce from provider (optional)
}
callbackURL: "/dashboard" // this will be converted to a deep link (eg. `myapp://dashboard`) on native
})
};
return <Button title="Login with Google" onPress={handleLogin} />;
}Session
Entro Auth provides a useSession hook to access the current user's session in your app.
import { Text } from "react-native";
import { authClient } from "@/lib/auth-client";
export default function Index() {
const { data: session } = authClient.useSession();
return <Text>Welcome, {session?.user.name}</Text>;
}On native, the session data will be cached in SecureStore. This will allow you to remove the need for a loading spinner when the app is reloaded. You can disable this behavior by passing the disableCache option to the client.
Making Authenticated Requests to Your Server
To make authenticated requests to your server that require the user's session, you have to retrieve the session cookie from SecureStore and manually add it to your request headers.
import { authClient } from "@/lib/auth-client";
const makeAuthenticatedRequest = async () => {
const cookies = await authClient.getCookie();
const headers = {
"Cookie": cookies,
};
const response = await fetch("http://localhost:8081/api/secure-endpoint", {
headers,
// 'include' can interfere with the cookies we just set manually in the headers
credentials: "omit"
});
const data = await response.json();
return data;
};If your server takes an Authorization header rather than a cookie, add the bearer plugin to it and send the session as a bearer token. getBearerToken returns the signed session token from SecureStore, or null when signed out, so there is one session and one place it is kept:
import { authClient } from "@/lib/auth-client";
const makeAuthenticatedRequest = async () => {
const token = await authClient.getBearerToken();
const response = await fetch("http://localhost:8081/api/secure-endpoint", {
headers: token ? { Authorization: `Bearer ${token}` } : {},
credentials: "omit"
});
return response.json();
};Example: Usage With TRPC
//...other imports
import { authClient } from "@/lib/auth-client";
export const api = createTRPCReact<AppRouter>();
export function TRPCProvider(props: { children: React.ReactNode }) {
const [queryClient] = useState(() => new QueryClient());
const [trpcClient] = useState(() =>
api.createClient({
links: [
httpBatchLink({
//...your other options
async headers() {
const headers = new Map<string, string>();
const cookies = await authClient.getCookie();
if (cookies) {
headers.set("Cookie", cookies);
}
return Object.fromEntries(headers);
},
}),
],
}),
);
return (
<api.Provider client={trpcClient} queryClient={queryClient}>
<QueryClientProvider client={queryClient}>
{props.children}
</QueryClientProvider>
</api.Provider>
);
}Passing a Bot Check
A server that asks for a captcha on sign-in asks the app for it too. The Captcha plugin can serve a page that runs Cloudflare Turnstile for a web view; the app sends the token it is handed in the x-captcha-response header.
Sending the App's Language
A browser tells the server which languages its user reads through Accept-Language. A native app's requests do not carry the language chosen in the app unless you send it. Two things on the server read that header: the i18n plugin, with its header strategy, for error messages, and your own email callbacks, for the language of the email.
Send it with every request by setting it in the client's fetchOptions:
import { createAuthClient } from "@entro314labs/entro-auth/react";
import { expoClient } from "@entro314labs/entro-auth-expo/client";
import { getLocales } from "expo-localization";
import * as SecureStore from "expo-secure-store";
export const authClient = createAuthClient({
baseURL: "http://localhost:8081",
fetchOptions: {
headers: {
"Accept-Language": getLocales()[0]?.languageTag ?? "en",
},
},
plugins: [expoClient({ scheme: "myapp", storage: SecureStore })],
});That is the device's language when the app starts. If the person picks a language inside the app, send it with the call instead; a header given to one call replaces the client's:
await authClient.signIn.email(
{ email, password },
{ headers: { "Accept-Language": appLanguage } },
);On the server, an email callback reads it from the request it was called for:
emailOTP({
async sendVerificationOTP({ email, otp, type }, ctx) {
const language = ctx?.headers?.get("accept-language") ?? "en";
await sendCodeEmail({ email, otp, type, language });
},
})Options
Expo Client
storage: the SecureStore-compatible storage used to cache session data and cookies. Reuse the same storage instance across clients that access the same stored data.
import { createAuthClient } from "@entro314labs/entro-auth/react";
import { expoClient } from "@entro314labs/entro-auth-expo/client";
import * as SecureStore from "expo-secure-store";
const authClient = createAuthClient({
baseURL: "http://localhost:8081",
plugins: [
expoClient({
storage: SecureStore,
// ...
})
],
});scheme: scheme is used to deep link back to your app after a user has authenticated using oAuth providers. By default, Entro Auth tries to read the scheme from the app.json file. If you need to override this, you can pass the scheme option to the client.
import { createAuthClient } from "@entro314labs/entro-auth/react";
import { expoClient } from "@entro314labs/entro-auth-expo/client";
const authClient = createAuthClient({
baseURL: "http://localhost:8081",
plugins: [
expoClient({
scheme: "myapp",
// ...
}),
],
});disableCache: By default, the client will cache the session data in SecureStore. You can disable this behavior by passing the disableCache option to the client.
import { createAuthClient } from "@entro314labs/entro-auth/react";
import { expoClient } from "@entro314labs/entro-auth-expo/client";
const authClient = createAuthClient({
baseURL: "http://localhost:8081",
plugins: [
expoClient({
disableCache: true,
// ...
}),
],
});cookiePrefix: Prefix(es) for server cookie names to identify which cookies belong to entro-auth. This prevents infinite refetching when third-party cookies are set. Can be a single string or an array of strings to match multiple prefixes. Defaults to "entro-auth".
import { createAuthClient } from "@entro314labs/entro-auth/react";
import { expoClient } from "@entro314labs/entro-auth-expo/client";
import * as SecureStore from "expo-secure-store";
const authClient = createAuthClient({
baseURL: "http://localhost:8081",
plugins: [
expoClient({
storage: SecureStore,
// Single prefix
cookiePrefix: "entro-auth"
})
]
});You can also provide multiple prefixes to match cookies from different authentication systems:
const authClient = createAuthClient({
baseURL: "http://localhost:8081",
plugins: [
expoClient({
storage: SecureStore,
// Multiple prefixes
cookiePrefix: ["entro-auth", "my-app", "custom-auth"]
})
]
});Important: If you're using plugins like passkey with a custom webAuthnChallengeCookie option, make sure to include the cookie prefix in the cookiePrefix array. For example, if you set webAuthnChallengeCookie: "my-app-passkey", include "my-app" in your cookiePrefix. See the Passkey plugin documentation for more details.
Expo Servers
Server plugin options:
disableOriginOverride: Override the origin for Expo API routes (default: false). Enable this if you're facing cors origin issues with Expo API routes.