Home

Build a User Management App with Expo

This tutorial demonstrates how to build a basic user management app. The app authenticates and identifies the user, stores their profile information in the database, and allows the user to log in, update their profile details, and upload a profile photo. The app uses:

  • Supabase Database - a Postgres database for storing your user data and Row Level Security so data is protected and users can only access their own information.
  • Supabase Auth - users log in through magic links sent to their email (without having to set up passwords).
  • Supabase Storage - users can upload a profile photo.

Supabase User Management example

note

If you get stuck while working through this guide, refer to the full example on GitHub.

Project setup#

Before we start building we're going to set up our Database and API. This is as simple as starting a new Project in Supabase and then creating a "schema" inside the database.

Create a project#

  1. Create a new project in the Supabase Dashboard.
  2. Enter your project details.
  3. Wait for the new database to launch.

Set up the database schema#

Now we are going to set up the database schema. We can use the "User Management Starter" quickstart in the SQL Editor, or you can just copy/paste the SQL from below and run it yourself.

  1. Go to the SQL Editor page in the Dashboard.
  2. Click User Management Starter.
  3. Click Run.

Get the API Keys#

Now that you've created some database tables, you are ready to insert data using the auto-generated API. We just need to get the Project URL and anon key from the API settings.

  1. Go to the API Settings page in the Dashboard.
  2. Find your Project URL, anon, and service_role keys on this page.

Building the App#

Let's start building the React Native app from scratch.

Initialize a React Native app#

We can use expo to initialize an app called expo-user-management:


_10
npx create-expo-app -t expo-template-blank-typescript expo-user-management
_10
_10
cd expo-user-management

Then let's install the additional dependencies: supabase-js


_10
npm install @supabase/supabase-js
_10
npm install react-native-elements @react-native-async-storage/async-storage react-native-url-polyfill
_10
npx expo install expo-secure-store

Now let's create a helper file to initialize the Supabase client. We need the API URL and the anon key that you copied earlier. These variables will be exposed on the browser, and that's completely fine since we have Row Level Security enabled on our Database.

lib/supabase.ts

_27
import 'react-native-url-polyfill/auto'
_27
import * as SecureStore from 'expo-secure-store'
_27
import { createClient } from '@supabase/supabase-js'
_27
_27
const ExpoSecureStoreAdapter = {
_27
getItem: (key: string) => {
_27
return SecureStore.getItemAsync(key)
_27
},
_27
setItem: (key: string, value: string) => {
_27
SecureStore.setItemAsync(key, value)
_27
},
_27
removeItem: (key: string) => {
_27
SecureStore.deleteItemAsync(key)
_27
},
_27
}
_27
_27
const supabaseUrl = YOUR_REACT_NATIVE_SUPABASE_URL
_27
const supabaseAnonKey = YOUR_REACT_NATIVE_SUPABASE_ANON_KEY
_27
_27
export const supabase = createClient(supabaseUrl, supabaseAnonKey, {
_27
auth: {
_27
storage: ExpoSecureStoreAdapter as any,
_27
autoRefreshToken: true,
_27
persistSession: true,
_27
detectSessionInUrl: false,
_27
},
_27
})

Set up a Login component#

Let's set up a React Native component to manage logins and sign ups. Users would be able to sign in with their email and password.

components/Auth.tsx

_79
import React, { useState } from 'react'
_79
import { Alert, StyleSheet, View } from 'react-native'
_79
import { supabase } from '../lib/supabase'
_79
import { Button, Input } from 'react-native-elements'
_79
_79
export default function Auth() {
_79
const [email, setEmail] = useState('')
_79
const [password, setPassword] = useState('')
_79
const [loading, setLoading] = useState(false)
_79
_79
async function signInWithEmail() {
_79
setLoading(true)
_79
const { error } = await supabase.auth.signInWithPassword({
_79
email: email,
_79
password: password,
_79
})
_79
_79
if (error) Alert.alert(error.message)
_79
setLoading(false)
_79
}
_79
_79
async function signUpWithEmail() {
_79
setLoading(true)
_79
const { error } = await supabase.auth.signUp({
_79
email: email,
_79
password: password,
_79
})
_79
_79
if (error) Alert.alert(error.message)
_79
setLoading(false)
_79
}
_79
_79
return (
_79
<View style={styles.container}>
_79
<View style={[styles.verticallySpaced, styles.mt20]}>
_79
<Input
_79
label="Email"
_79
leftIcon={{ type: 'font-awesome', name: 'envelope' }}
_79
onChangeText={(text) => setEmail(text)}
_79
value={email}
_79
placeholder="email@address.com"
_79
autoCapitalize={'none'}
_79
/>
_79
</View>
_79
<View style={styles.verticallySpaced}>
_79
<Input
_79
label="Password"
_79
leftIcon={{ type: 'font-awesome', name: 'lock' }}
_79
onChangeText={(text) => setPassword(text)}
_79
value={password}
_79
secureTextEntry={true}
_79
placeholder="Password"
_79
autoCapitalize={'none'}
_79
/>
_79
</View>
_79
<View style={[styles.verticallySpaced, styles.mt20]}>
_79
<Button title="Sign in" disabled={loading} onPress={() => signInWithEmail()} />
_79
</View>
_79
<View style={styles.verticallySpaced}>
_79
<Button title="Sign up" disabled={loading} onPress={() => signUpWithEmail()} />
_79
</View>
_79
</View>
_79
)
_79
}
_79
_79
const styles = StyleSheet.create({
_79
container: {
_79
marginTop: 40,
_79
padding: 12,
_79
},
_79
verticallySpaced: {
_79
paddingTop: 4,
_79
paddingBottom: 4,
_79
alignSelf: 'stretch',
_79
},
_79
mt20: {
_79
marginTop: 20,
_79
},
_79
})

Account page#

After a user is signed in we can allow them to edit their profile details and manage their account.

Let's create a new component for that called Account.tsx.

components/Account.tsx

_120
import { useState, useEffect } from 'react'
_120
import { supabase } from '../lib/supabase'
_120
import { StyleSheet, View, Alert } from 'react-native'
_120
import { Button, Input } from 'react-native-elements'
_120
import { Session } from '@supabase/supabase-js'
_120
_120
export default function Account({ session }: { session: Session }) {
_120
const [loading, setLoading] = useState(true)
_120
const [username, setUsername] = useState('')
_120
const [website, setWebsite] = useState('')
_120
const [avatarUrl, setAvatarUrl] = useState('')
_120
_120
useEffect(() => {
_120
if (session) getProfile()
_120
}, [session])
_120
_120
async function getProfile() {
_120
try {
_120
setLoading(true)
_120
if (!session?.user) throw new Error('No user on the session!')
_120
_120
let { data, error, status } = await supabase
_120
.from('profiles')
_120
.select(`username, website, avatar_url`)
_120
.eq('id', session?.user.id)
_120
.single()
_120
if (error && status !== 406) {
_120
throw error
_120
}
_120
_120
if (data) {
_120
setUsername(data.username)
_120
setWebsite(data.website)
_120
setAvatarUrl(data.avatar_url)
_120
}
_120
} catch (error) {
_120
if (error instanceof Error) {
_120
Alert.alert(error.message)
_120
}
_120
} finally {
_120
setLoading(false)
_120
}
_120
}
_120
_120
async function updateProfile({
_120
username,
_120
website,
_120
avatar_url,
_120
}: {
_120
username: string
_120
website: string
_120
avatar_url: string
_120
}) {
_120
try {
_120
setLoading(true)
_120
if (!session?.user) throw new Error('No user on the session!')
_120
_120
const updates = {
_120
id: session?.user.id,
_120
username,
_120
website,
_120
avatar_url,
_120
updated_at: new Date(),
_120
}
_120
_120
let { error } = await supabase.from('profiles').upsert(updates)
_120
_120
if (error) {
_120
throw error
_120
}
_120
} catch (error) {
_120
if (error instanceof Error) {
_120
Alert.alert(error.message)
_120
}
_120
} finally {
_120
setLoading(false)
_120
}
_120
}
_120
_120
return (
_120
<View style={styles.container}>
_120
<View style={[styles.verticallySpaced, styles.mt20]}>
_120
<Input label="Email" value={session?.user?.email} disabled />
_120
</View>
_120
<View style={styles.verticallySpaced}>
_120
<Input label="Username" value={username || ''} onChangeText={(text) => setUsername(text)} />
_120
</View>
_120
<View style={styles.verticallySpaced}>
_120
<Input label="Website" value={website || ''} onChangeText={(text) => setWebsite(text)} />
_120
</View>
_120
_120
<View style={[styles.verticallySpaced, styles.mt20]}>
_120
<Button
_120
title={loading ? 'Loading ...' : 'Update'}
_120
onPress={() => updateProfile({ username, website, avatar_url: avatarUrl })}
_120
disabled={loading}
_120
/>
_120
</View>
_120
_120
<View style={styles.verticallySpaced}>
_120
<Button title="Sign Out" onPress={() => supabase.auth.signOut()} />
_120
</View>
_120
</View>
_120
)
_120
}
_120
_120
const styles = StyleSheet.create({
_120
container: {
_120
marginTop: 40,
_120
padding: 12,
_120
},
_120
verticallySpaced: {
_120
paddingTop: 4,
_120
paddingBottom: 4,
_120
alignSelf: 'stretch',
_120
},
_120
mt20: {
_120
marginTop: 20,
_120
},
_120
})

Launch!#

Now that we have all the components in place, let's update App.tsx:

App.tsx

_27
import 'react-native-url-polyfill/auto'
_27
import { useState, useEffect } from 'react'
_27
import { supabase } from './lib/supabase'
_27
import Auth from './components/Auth'
_27
import Account from './components/Account'
_27
import { View } from 'react-native'
_27
import { Session } from '@supabase/supabase-js'
_27
_27
export default function App() {
_27
const [session, setSession] = useState<Session | null>(null)
_27
_27
useEffect(() => {
_27
supabase.auth.getSession().then(({ data: { session } }) => {
_27
setSession(session)
_27
})
_27
_27
supabase.auth.onAuthStateChange((_event, session) => {
_27
setSession(session)
_27
})
_27
}, [])
_27
_27
return (
_27
<View>
_27
{session && session.user ? <Account key={session.user.id} session={session} /> : <Auth />}
_27
</View>
_27
)
_27
}

Once that's done, run this in a terminal window:


_10
npm start

And then press the appropriate key for the environment you want to test the app in and you should see the completed app.

Bonus: Profile photos#

Every Supabase project is configured with Storage for managing large files like photos and videos.

Additional dependency installation#

You will need a file picker that works on the environment you will build the project for, we will use react-native-document-picker in this example.


_10
expo install react-native-document-picker

Create an upload widget#

Let's create an avatar for the user so that they can upload a profile photo. We can start by creating a new component:

components/Avatar.tsx

_124
import { useState, useEffect } from 'react'
_124
import { supabase } from '../lib/supabase'
_124
import { StyleSheet, View, Alert, Image, Button } from 'react-native'
_124
import DocumentPicker, { isCancel, isInProgress, types } from 'react-native-document-picker'
_124
_124
interface Props {
_124
size: number
_124
url: string | null
_124
onUpload: (filePath: string) => void
_124
}
_124
_124
export default function Avatar({ url, size = 150, onUpload }: Props) {
_124
const [uploading, setUploading] = useState(false)
_124
const [avatarUrl, setAvatarUrl] = useState<string | null>(null)
_124
const avatarSize = { height: size, width: size }
_124
_124
useEffect(() => {
_124
if (url) downloadImage(url)
_124
}, [url])
_124
_124
async function downloadImage(path: string) {
_124
try {
_124
const { data, error } = await supabase.storage.from('avatars').download(path)
_124
_124
if (error) {
_124
throw error
_124
}
_124
_124
const fr = new FileReader()
_124
fr.readAsDataURL(data)
_124
fr.onload = () => {
_124
setAvatarUrl(fr.result as string)
_124
}
_124
} catch (error) {
_124
if (error instanceof Error) {
_124
console.log('Error downloading image: ', error.message)
_124
}
_124
}
_124
}
_124
_124
async function uploadAvatar() {
_124
try {
_124
setUploading(true)
_124
_124
const file = await DocumentPicker.pickSingle({
_124
presentationStyle: 'fullScreen',
_124
copyTo: 'cachesDirectory',
_124
type: types.images,
_124
mode: 'open',
_124
})
_124
_124
const photo = {
_124
uri: file.fileCopyUri,
_124
type: file.type,
_124
name: file.name,
_124
}
_124
_124
const formData = new FormData()
_124
formData.append('file', photo)
_124
_124
const fileExt = file.name.split('.').pop()
_124
const filePath = `${Math.random()}.${fileExt}`
_124
_124
let { error } = await supabase.storage.from('avatars').upload(filePath, formData)
_124
_124
if (error) {
_124
throw error
_124
}
_124
_124
onUpload(filePath)
_124
} catch (error) {
_124
if (isCancel(error)) {
_124
console.warn('cancelled')
_124
// User cancelled the picker, exit any dialogs or menus and move on
_124
} else if (isInProgress(error)) {
_124
console.warn('multiple pickers were opened, only the last will be considered')
_124
} else if (error instanceof Error) {
_124
Alert.alert(error.message)
_124
} else {
_124
throw error
_124
}
_124
} finally {
_124
setUploading(false)
_124
}
_124
}
_124
_124
return (
_124
<View>
_124
{avatarUrl ? (
_124
<Image
_124
source={{ uri: avatarUrl }}
_124
accessibilityLabel="Avatar"
_124
style={[avatarSize, styles.avatar, styles.image]}
_124
/>
_124
) : (
_124
<View style={[avatarSize, styles.avatar, styles.noImage]} />
_124
)}
_124
<View>
_124
<Button
_124
title={uploading ? 'Uploading ...' : 'Upload'}
_124
onPress={uploadAvatar}
_124
disabled={uploading}
_124
/>
_124
</View>
_124
</View>
_124
)
_124
}
_124
_124
const styles = StyleSheet.create({
_124
avatar: {
_124
borderRadius: 5,
_124
overflow: 'hidden',
_124
maxWidth: '100%',
_124
},
_124
image: {
_124
objectFit: 'cover',
_124
paddingTop: 0,
_124
},
_124
noImage: {
_124
backgroundColor: '#333',
_124
border: '1px solid rgb(200, 200, 200)',
_124
borderRadius: 5,
_124
},
_124
})

Add the new widget#

And then we can add the widget to the Account page:

components/Account.tsx

_22
// Import the new component
_22
import Avatar from './Avatar'
_22
_22
// ...
_22
return (
_22
<View>
_22
{/* Add to the body */}
_22
<View>
_22
<Avatar
_22
size={200}
_22
url={avatarUrl}
_22
onUpload={(url: string) => {
_22
setAvatarUrl(url)
_22
updateProfile({ username, website, avatar_url: url })
_22
}}
_22
/>
_22
</View>
_22
{/* ... */}
_22
</View>
_22
)
_22
}
_22
// ...

Now you will need to run the prebuild command to get the application working on your chosen platform.


_10
expo prebuild

Storage management#

If you upload additional profile photos, they'll accumulate in the avatars bucket because of their random names with only the latest being referenced from public.profiles and the older versions getting orphaned.

To automatically remove obsolete storage objects, extend the database triggers. Note that it is not sufficient to delete the objects from the storage.objects table because that would orphan and leak the actual storage objects in the S3 backend. Instead, invoke the storage API within Postgres via the http extension.

Enable the http extension for the extensions schema in the Dashboard. Then, define the following SQL functions in the SQL Editor to delete storage objects via the API:


_34
create or replace function delete_storage_object(bucket text, object text, out status int, out content text)
_34
returns record
_34
language 'plpgsql'
_34
security definer
_34
as $$
_34
declare
_34
project_url text := '<YOURPROJECTURL>';
_34
service_role_key text := '<YOURSERVICEROLEKEY>'; -- full access needed
_34
url text := project_url||'/storage/v1/object/'||bucket||'/'||object;
_34
begin
_34
select
_34
into status, content
_34
result.status::int, result.content::text
_34
FROM extensions.http((
_34
'DELETE',
_34
url,
_34
ARRAY[extensions.http_header('authorization','Bearer '||service_role_key)],
_34
NULL,
_34
NULL)::extensions.http_request) as result;
_34
end;
_34
$$;
_34
_34
create or replace function delete_avatar(avatar_url text, out status int, out content text)
_34
returns record
_34
language 'plpgsql'
_34
security definer
_34
as $$
_34
begin
_34
select
_34
into status, content
_34
result.status, result.content
_34
from public.delete_storage_object('avatars', avatar_url) as result;
_34
end;
_34
$$;

Next, add a trigger that removes any obsolete avatar whenever the profile is updated or deleted:


_29
create or replace function delete_old_avatar()
_29
returns trigger
_29
language 'plpgsql'
_29
security definer
_29
as $$
_29
declare
_29
status int;
_29
content text;
_29
begin
_29
if coalesce(old.avatar_url, '') <> ''
_29
and (tg_op = 'DELETE' or (old.avatar_url <> new.avatar_url)) then
_29
select
_29
into status, content
_29
result.status, result.content
_29
from public.delete_avatar(old.avatar_url) as result;
_29
if status <> 200 then
_29
raise warning 'Could not delete avatar: % %', status, content;
_29
end if;
_29
end if;
_29
if tg_op = 'DELETE' then
_29
return old;
_29
end if;
_29
return new;
_29
end;
_29
$$;
_29
_29
create trigger before_profile_changes
_29
before update of avatar_url or delete on public.profiles
_29
for each row execute function public.delete_old_avatar();

Finally, delete the public.profile row before a user is deleted. If this step is omitted, you won't be able to delete users without first manually deleting their avatar image.


_14
create or replace function delete_old_profile()
_14
returns trigger
_14
language 'plpgsql'
_14
security definer
_14
as $$
_14
begin
_14
delete from public.profiles where id = old.id;
_14
return old;
_14
end;
_14
$$;
_14
_14
create trigger before_delete_user
_14
before delete on auth.users
_14
for each row execute function public.delete_old_profile();

At this stage you have a fully functional application!