Your first app with React Native
A to-do list for iPhone and Android where people sign up and see only their own todos. It uses Expo and @espobase/client; the database and keys come from the dashboard.
1. Create a project and a table
In the dashboard, create a project. Open SQL Editor and run:
create table todos ( id bigint generated by default as identity primary key, owner_id uuid not null default espobase.user_id(), title text not null, done boolean not null default false, created_at timestamptz not null default now() ); -- Row level security is already on. Each signed-in user sees and changes only their own todos: create policy "Users manage their own todos" on todos for all using (owner_id = espobase.user_id()) with check (owner_id = espobase.user_id());
2. Settings and keys
- API: create a publishable key and copy it now; keys are only shown when created. Never put a secret key (
eb_sk_…) in an app: anyone can unpack an app and read it. - Authentication › Settings: add your app's link under Allowed redirect URLs, for example
myapp://auth/callback, wheremyappis theschemein your app.json. Confirmation emails and social sign-in return to it.
3. Install
npm install @espobase/client npx expo install @react-native-async-storage/async-storage react-native-get-random-values react-native-url-polyfill expo-web-browser expo-linking
React Native lacks a few things browsers have. Two small packages fill them in; import them before anything else:
# .env (Expo reads EXPO_PUBLIC_ variables; the PUBLISHABLE key is safe in an app) EXPO_PUBLIC_ESPOBASE_URL=https://api.espobase.com/project/<your project ref> EXPO_PUBLIC_ESPOBASE_KEY=eb_pk_…
4. The client
A phone has no localStorage, so give the client a place to keep the session. It is refreshed for you, and the user stays signed in when the app restarts.
// lib/espobase.ts
import "react-native-get-random-values"; // crypto.getRandomValues
import "react-native-url-polyfill/auto"; // a complete URL class
import AsyncStorage from "@react-native-async-storage/async-storage";
import { createClient } from "@espobase/client";
export const espobase = createClient(
process.env.EXPO_PUBLIC_ESPOBASE_URL!,
process.env.EXPO_PUBLIC_ESPOBASE_KEY!,
{ auth: { storage: AsyncStorage } },
);5. Sign-up and sign-in
import * as Linking from "expo-linking";
import { espobase } from "@/lib/espobase";
// myapp://auth/callback (the scheme comes from app.json). Add it under Authentication › Settings.
const redirectTo = Linking.createURL("auth/callback");
await espobase.auth.signUp({ email, password, options: { redirectTo } });
await espobase.auth.signInWithPassword({ email, password });
// The confirmation email opens the app at redirectTo#type=signup&token=…
Linking.addEventListener("url", async ({ url }) => {
const token = new URLSearchParams(url.split("#")[1] ?? "").get("token");
if (token) await espobase.auth.verifyEmail({ token });
});
// Re-render when the user signs in or out.
espobase.auth.onAuthStateChange((_event, session) => setSession(session));With email confirmation on, the user gets a link that opens your app at the address you passed as redirectTo, with the token after a #. Confirm it with espobase.auth.verifyEmail({ token }).
7. Read and write your data
import { useEffect, useState } from "react";
import { espobase } from "@/lib/espobase";
export function useTodos() {
const [todos, setTodos] = useState<{ id: number; title: string; done: boolean }[]>([]);
useEffect(() => {
espobase.from("todos").select("*").order("created_at").then(({ data }) => setTodos(data ?? []));
}, []);
return todos;
}
// owner_id fills itself in (its default is espobase.user_id()).
await espobase.from("todos").insert({ title: "Buy milk" });Every request carries the signed-in user, and the database applies your rule. A user who isn't signed in gets an empty list, and nobody can read or change someone else's todos, even by calling the API directly.
8. Upload a photo
Create a bucket under Storage and add a policy so each user can write to their own folder (see the file uploads guide). Pass the file's bytes (an ArrayBuffer) to upload: File uploads
import * as ImagePicker from "expo-image-picker";
import { espobase } from "@/lib/espobase";
const picked = await ImagePicker.launchImageLibraryAsync({ mediaTypes: ["images"] });
if (!picked.canceled) {
const asset = picked.assets[0]!;
const bytes = await (await fetch(asset.uri)).arrayBuffer();
const { data: session } = await espobase.auth.getSession();
const userId = session.session!.user.id;
await espobase.storage.from("photos").upload(`${userId}/photo.jpg`, bytes, { contentType: "image/jpeg" });
}Good to know
- Use a development build (
npx expo run:iosorrun:android) rather than Expo Go for sign-in links: Expo Go's address changes with your network, so it can't be registered once. - Other React Native setups work the same way: install the same packages, import the two polyfills first and pass a storage object to
createClient. - Realtime works too: React Native has WebSockets built in, so
espobase.realtimeneeds nothing extra.
6. Sign in with Google or GitHub
import * as WebBrowser from "expo-web-browser"; import * as Linking from "expo-linking"; import { espobase } from "@/lib/espobase"; export async function signInWithGoogle() { const redirectTo = Linking.createURL("auth/callback"); const { data } = await espobase.auth.signInWithOAuth({ provider: "google", options: { redirectTo, skipBrowserRedirect: true }, }); const result = await WebBrowser.openAuthSessionAsync(data!.url, redirectTo); if (result.type !== "success") return; // cancelled const code = new URL(result.url).searchParams.get("code"); if (code) await espobase.auth.exchangeCodeForSession(code); }Turn the provider on under Authentication › Providers first. The app opens the provider in the system browser and gets the user back through your app link;
exchangeCodeForSessionfinishes the sign-in. Only this app can finish it: the one-time secret stays on the phone.