React Native builds native Android and iOS apps from React components, and Expo is a framework built on top of it. This page connects a React Native app to a remote SurrealDB instance with the JavaScript SDK, keeps the connection alive across the mobile app lifecycle, stores session tokens securely, and runs queries and live queries.
The steps apply to an Expo project and to a bare project created with the React Native Community CLI. Where the two differ, the step has one tab for each, and the tabs switch together across the page.
Prerequisites
A basic understanding of React
An Expo project on SDK 54 or newer that uses Expo Router, created with
npx create-expo-app, or a React Native project on 0.79 or newer, created withnpx @react-native-community/cli initA running SurrealDB instance that the device can reach
What is different on mobile
The SDK surface is the same one used in React applications, but four constraints apply on Android and iOS that do not apply in a browser.
Embedded engines are not supported. The WebAssembly engine needs a WebAssembly runtime, which Hermes does not provide. The Node.js engine is a native Node addon and cannot be loaded by React Native. A mobile app cannot run SurrealDB on the device itself, so every connection is a remote connection.
The JavaScript engine is not a browser. Hermes leaves out several web APIs that the SDK depends on. Expo installs them as globals, and a bare React Native project installs them as polyfills before the SDK loads.
Your JavaScript bundle ships to the device. Anyone who installs the app can read the values you compile into it. Use record access for end users, and keep system user credentials on a server.
The connection does not survive backgrounding. Both platforms suspend your process shortly after the user leaves the app, which closes the socket. You reconnect when the app returns to the foreground.
Supported connection protocols
| Protocol | Supported | Notes |
|---|---|---|
wss:// | Yes | Long-lived connection. Required for live queries. |
https:// | Yes | Stateless requests. No live queries. A bare React Native project needs the ReadableStream global. |
ws://, http:// | Development only | Blocked by default on both platforms. See allowing unencrypted connections in development. |
Use wss:// unless you only need occasional one-off requests. A WebSocket connection stays open, so the session stays authenticated between calls, and it is the only protocol that supports live queries.
Installing dependencies
In addition to surrealdb, this guide uses @tanstack/react-query to manage the asynchronous connection state, and a keystore library to keep session tokens in the platform keystore.
Install the SDK with npx expo install rather than your package manager directly. It picks dependency versions that match your Expo SDK. expo-secure-store holds the session tokens.
npx expo install surrealdb @tanstack/react-query expo-secure-storeThe SDK is plain JavaScript, so it works in Expo Go as well as in a development build.
Follow the installation guide for more information on how to install the SDK in your project.
Installing the required polyfills
The SDK needs TextEncoder, TextDecoder, URL and URLSearchParams at runtime.
The expo package installs all four as globals on Android and iOS, so an Expo project needs no polyfills. Continue with the next step.
Allowing unencrypted connections in development
Android blocks cleartext traffic from API level 28, and iOS blocks it through App Transport Security. A local SurrealDB server listens on plain ws://, so a development build needs an exception for it.
Install expo-build-properties, which applies the Android setting at build time:
npx expo install expo-build-propertiesThen add the following to app.json and rebuild the development build.
{
"expo": {
"ios": {
"infoPlist": {
"NSAppTransportSecurity": {
"NSAllowsLocalNetworking": true
}
}
},
"plugins": [
[
"expo-build-properties",
{
"android": {
"usesCleartextTraffic": true
}
}
]
]
}
} Both settings weaken transport security for the whole app. Apply them to a development build only, and connect over wss:// in the builds you ship.
Reaching your database from a device
On a phone or emulator, localhost means the device itself, not your development machine. Set the endpoint to the address that the device can reach.
| Where the app runs | Address to use |
|---|---|
| iOS simulator | ws://127.0.0.1:8000 |
| Android emulator | ws://10.0.2.2:8000 |
| Physical device | ws://<your-machine-lan-ip>:8000, for example ws://192.168.1.24:8000 |
| Production | Your deployed hostname over wss:// |
A physical device reaches your machine over the network, so start the server with --bind 0.0.0.0:8000 when you test on one. The default, 127.0.0.1:8000, accepts connections from the machine itself only, which includes the iOS simulator and the Android emulator.


Put the endpoint in a .env file at the root of the project:
EXPO_PUBLIC_SURREAL_ENDPOINT=ws://10.0.2.2:8000Variables prefixed with EXPO_PUBLIC_ are inlined into the bundle at build time and are readable inside your app as process.env.EXPO_PUBLIC_SURREAL_ENDPOINT. Use them for the endpoint and never for credentials. Restart the development server after changing the file.
Creating the connection provider
Initialise the SDK in a Context Provider so the Surreal client is available anywhere in your component tree. The provider below manages the connection lifecycle, tracks connection status through TanStack Query, closes the socket when the app moves to the background, and reconnects when it becomes active again. It is the same file for an Expo project and a React Native CLI project.
The params prop accepts the same options as .connect(), including namespace, database, and authentication.
import { Surreal } from "surrealdb";
import { useMutation } from "@tanstack/react-query";
import { AppState } from "react-native";
import React, { createContext, useCallback, useContext, useEffect, useMemo, useState } from "react";
interface SurrealProviderProps {
children: React.ReactNode;
endpoint: string;
client?: Surreal;
params?: Parameters<Surreal["connect"]>[1];
}
interface SurrealProviderState {
client: Surreal;
isConnecting: boolean;
isSuccess: boolean;
isError: boolean;
error: unknown;
connect: () => Promise<true>;
close: () => Promise<true>;
}
const SurrealContext = createContext<SurrealProviderState | undefined>(undefined);
export function SurrealProvider({ children, client, endpoint, params }: SurrealProviderProps) {
const [instance] = useState(() => client ?? new Surreal());
const {
mutateAsync: connectMutation,
isPending,
isSuccess,
isError,
error,
reset,
} = useMutation({
mutationFn: () => instance.connect(endpoint, params),
});
const connect = useCallback(() => connectMutation(), [connectMutation]);
const close = useCallback(() => instance.close(), [instance]);
useEffect(() => {
connect();
return () => {
reset();
instance.close();
};
}, [connect, reset, instance]);
useEffect(() => {
const subscription = AppState.addEventListener("change", (state) => {
if (state === "active" && instance.status === "disconnected") {
connect();
} else if (state === "background") {
instance.close();
}
});
return () => subscription.remove();
}, [instance, connect]);
const value: SurrealProviderState = useMemo(
() => ({ client: instance, isConnecting: isPending, isSuccess, isError, error, connect, close }),
[instance, isPending, isSuccess, isError, error, connect, close],
);
return <SurrealContext.Provider value={value}>{children}</SurrealContext.Provider>;
}
export function useSurreal() {
const context = useContext(SurrealContext);
if (!context) throw new Error("useSurreal must be used within a SurrealProvider");
return context;
}
export function useSurrealClient() {
return useSurreal().client;
}The handler closes the connection on background but ignores inactive. On iOS, inactive also fires for the app switcher and for incoming calls, which are usually too short to be worth dropping the socket.
Wrapping your application
Mount QueryClientProvider and SurrealProvider around every screen of the app, so no screen queries a connection that does not exist.
The authentication option below signs in as a system user, which is enough to try the app against a local database. The next section replaces it with record access.
Expo Router renders app/_layout.tsx around every route, which makes it the place to mount providers. Wrap the navigation stack:
import { Stack } from "expo-router";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { SurrealProvider } from "../SurrealProvider";
const queryClient = new QueryClient();
export default function RootLayout() {
return (
<QueryClientProvider client={queryClient}>
<SurrealProvider
endpoint={process.env.EXPO_PUBLIC_SURREAL_ENDPOINT!}
params={{
namespace: "surrealdb",
database: "docs",
authentication: {
username: "root",
password: "secret",
},
}}
>
<Stack />
</SurrealProvider>
</QueryClientProvider>
);
} The root credentials above are for a local database you are experimenting with. Everything you compile into a mobile app is readable by anyone who installs it, so a released app must never carry them. Use record access, described in the next section, to sign real users in instead.
Handling authentication
Sign users in with record access and keep the resulting tokens in the platform keystore, so the session survives an app restart.
import * as SecureStore from "expo-secure-store";
import { useEffect } from "react";
import { useSurreal } from "./SurrealProvider";
export const ACCESS_KEY = "surreal.access";
export const REFRESH_KEY = "surreal.refresh";
export function useAuth() {
const { client } = useSurreal();
useEffect(() => {
return client.subscribe("auth", async (tokens) => {
if (tokens) {
await SecureStore.setItemAsync(ACCESS_KEY, tokens.access);
if (tokens.refresh) await SecureStore.setItemAsync(REFRESH_KEY, tokens.refresh);
} else {
await SecureStore.deleteItemAsync(ACCESS_KEY);
await SecureStore.deleteItemAsync(REFRESH_KEY);
}
});
}, [client]);
async function login(email: string, password: string) {
return client.signin({
namespace: "surrealdb",
database: "docs",
access: "account",
variables: { email, password },
});
}
async function register(email: string, password: string) {
return client.signup({
namespace: "surrealdb",
database: "docs",
access: "account",
variables: { email, password },
});
}
async function logout() {
return client.invalidate();
}
return { login, register, logout };
} expo-secure-store is backed by the iOS keychain and by Android's keystore. iOS rejects values above roughly 2048 bytes, so store the access and refresh tokens under separate keys rather than as one JSON object.
The auth event fires on sign in, sign up, token refresh, and invalidation, and .subscribe() returns the function that removes the listener.
Restoring a session on launch
Pass a function to the authentication connection option, in place of the root credentials. The SDK calls it while opening the connection and again whenever it needs to re-authenticate after a reconnect. The option accepts a token string or null.
SecureStore.getItemAsync() returns string | null, which is exactly what the option expects.
import * as SecureStore from "expo-secure-store";
import { ACCESS_KEY } from "../useAuth";
<SurrealProvider
endpoint={process.env.EXPO_PUBLIC_SURREAL_ENDPOINT!}
params={{
namespace: "surrealdb",
database: "docs",
authentication: () => SecureStore.getItemAsync(ACCESS_KEY),
}}
>If the stored access token has expired and you also hold a refresh token, exchange the pair with .authenticate() instead.
const access = await SecureStore.getItemAsync(ACCESS_KEY);
const refresh = await SecureStore.getItemAsync(REFRESH_KEY);
if (access) {
await client.authenticate(refresh ? { access, refresh } : access);
} Once you call .signin(), .signup(), or .authenticate(), the authentication connection option is ignored for the rest of that session. Choose one of the two approaches per session rather than mixing them.
Executing queries
Use the useSurreal() hook to reach the Surreal instance and the connection state from any component, or useSurrealClient() when you only need the client. All query methods are available on the client, including .query(), .select(), and .create().
Writing records
Use .create() to add a record to a table, with .content() holding the fields you want to store. Pass a Table to let the database generate the ID, or a RecordId to choose it.
import { RecordId, Table } from "surrealdb";
const users = new Table("users");
// Create a record with an ID generated by the database
const [jaime] = await client.create(users).content({
name: "Jaime",
email: "jaime@example.com",
});
console.log(jaime);
// { id: users:0dxay1r0dc9c1cn8vzuq, name: 'Jaime', email: 'jaime@example.com' }
// Create a record with an ID you choose
const tobie = await client.create(new RecordId(users, "tobie")).content({
name: "Tobie",
email: "tobie@example.com",
});
console.log(tobie);
// { id: users:tobie, name: 'Tobie', email: 'tobie@example.com' }.create() on a Table returns an array holding the new record, and on a RecordId it returns the record itself. Every record has an ID made of its table name and a unique key, written as users:tobie. You do not need to create the table first - SurrealDB adds it on the first write.
Reading and displaying records
.select() reads records back. Pass a Table to read all of them, or a RecordId to read one, and chain .where() and .limit() to narrow the result. Expression helpers such as eq and lt build the conditions for .where().
Gate the query on isSuccess so it runs once the connection is open, and again after each reconnect.
import { useEffect, useState } from "react";
import { ActivityIndicator, FlatList, Text, View } from "react-native";
import { Table } from "surrealdb";
import { useSurreal } from "../SurrealProvider";
interface User {
id: string;
name: string;
email: string;
}
export default function UserList() {
const { client, isConnecting, isSuccess, isError, error } = useSurreal();
const [users, setUsers] = useState<User[]>([]);
useEffect(() => {
if (!isSuccess) return;
client.select<User>(new Table("users"))
.then(setUsers)
.catch(console.error);
}, [client, isSuccess]);
if (isConnecting) return <ActivityIndicator />;
if (isError) return <Text>Connection failed: {String(error)}</Text>;
return (
<FlatList
data={users}
keyExtractor={(user) => String(user.id)}
renderItem={({ item }) => (
<View>
<Text>{item.name}</Text>
<Text>{item.email}</Text>
</View>
)}
/>
);
}Run the app and the list shows the users you created. If it shows the connection failure message instead, the address is usually the cause: check the table in reaching your database from a device and confirm that SurrealDB is running.
Subscribing to live queries
Live queries push changes to the device as they happen, which removes the need to poll on a metered connection. They require a WebSocket connection.
Because the provider closes the socket on background, tie the subscription to isSuccess as well. The effect then recreates the subscription every time the connection reopens.
import { useEffect, useState } from "react";
import { Table } from "surrealdb";
import { useSurreal } from "./SurrealProvider";
interface Message {
id: string;
body: string;
}
export function useLiveMessages() {
const { client, isSuccess } = useSurreal();
const [messages, setMessages] = useState<Message[]>([]);
useEffect(() => {
if (!isSuccess) return;
const pending = client.live<Message>(new Table("messages"));
pending
.then((live) => {
live.subscribe((action, result) => {
if (action === "CREATE") {
setMessages((current) => [...current, result]);
}
});
})
.catch(console.error);
return () => {
pending.then((live) => live.kill()).catch(() => {});
};
}, [client, isSuccess]);
return messages;
}Troubleshooting
| Symptom | Cause |
|---|---|
ReferenceError: Property 'TextDecoder' doesn't exist | In a React Native CLI project, the polyfill imports are missing, or they sit below the SDK import in the entry file. |
The endpoint fails to parse, or URL throws on construction | In a React Native CLI project, react-native-url-polyfill/auto is not imported. |
Network request failed on Android, works in the browser | The endpoint uses localhost. Use 10.0.2.2 on the emulator or the LAN address on a device. |
| Connection fails on a physical device, works on the simulator | The server listens on 127.0.0.1 only. Start it with --bind 0.0.0.0:8000. |
| Connection hangs, then fails with no server log entry | Cleartext traffic is blocked. Switch to wss:// or apply the development configuration. |
The Expo app still uses the old endpoint after editing .env | EXPO_PUBLIC_ variables are inlined at build time. Restart the development server. |
Unable to resolve module node:util | Metro resolved the SDK's server build. Remove node from unstable_conditionNames in metro.config.js. |
| Queries fail after the app returns from the background | The query ran before the socket reopened. Gate it on isSuccess from the provider. |
| Live query stops delivering after backgrounding | The subscription was created against the closed connection. Recreate it when isSuccess becomes true again. |
Learn more
Connecting to SurrealDB for connection protocols and reconnection behaviour
Authentication for signing in, signing up, and token management
Executing queries for query builders and raw SurrealQL
Live queries for real-time subscriptions
React for the same provider in a web application
JavaScript SDK API reference for the complete method reference