Build a User Management App with Expo React Native
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 - allow users to sign up and log in.
- Supabase Storage - allow users to upload a profile photo.

If you get stuck while working through this guide, refer to the full example on GitHub.
Project setup
Before you start building you need to set up the Database and API. You can do this by starting a new Project in Supabase and then creating a "schema" inside the database.
Create a project
- Create a new project in the Supabase Dashboard.
- Enter your project details.
- Wait for the new database to launch.
Set up the database schema
Now set up the database schema. You can use the "User Management Starter" quickstart in the SQL Editor, or you can copy/paste the SQL from below and run it.
- Go to the SQL Editor page in the Dashboard.
- Click User Management Starter under the Community > Quickstarts tab.
- Click Run.
You can pull the database schema down to your local project by running the db pull command. Read the local development docs for detailed instructions.
1supabase link --project-ref <project-id>2# You can get <project-id> from your project's dashboard URL: https://supabase.com/dashboard/project/<project-id>3supabase db pullGet API details
Now that you've created some database tables, you are ready to insert data using the auto-generated API.
To do this, you need to get the Project URL and key. Get the URL from the API settings section of a project and the key from the the API Keys section of a project's Settings page.
Changes to API keys
Supabase is changing the way keys work to improve project security and developer experience. You can read the full announcement, but in the transition period, you can use both the current anon and service_role keys and the new publishable key with the form sb_publishable_xxx which will replace the older keys.
To get the key values, open the API Keys section of a project's Settings page and do the following:
- For legacy keys, copy the
anonkey for client-side operations and theservice_rolekey for server-side operations from the Legacy API Keys tab. - For new keys, open the API Keys tab, if you don't have a publishable key already, click Create new API Keys, and copy the value from the Publishable key section.
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:
1npx create-expo-app -t expo-template-blank-typescript expo-user-management23cd expo-user-managementThen let's install the additional dependencies: supabase-js
1npx expo install @supabase/supabase-js @react-native-async-storage/async-storage @rneui/themedNow let's create a helper file to initialize the Supabase client. We need the API URL and the key that you copied earlier. These variables are safe to expose in your Expo app since Supabase has Row Level Security enabled on your Database.
1import AsyncStorage from '@react-native-async-storage/async-storage'2import { createClient } from '@supabase/supabase-js'34const supabaseUrl = YOUR_REACT_NATIVE_SUPABASE_URL5const supabasePublishableKey = YOUR_REACT_NATIVE_SUPABASE_PUBLISHABLE_KEY67export const supabase = createClient(supabaseUrl, supabasePublishableKey, {8 auth: {9 storage: AsyncStorage,10 autoRefreshToken: true,11 persistSession: true,12 detectSessionInUrl: false,13 },14})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.
1import React, { useState } from 'react'2import { Alert, StyleSheet, View, AppState } from 'react-native'3import { supabase } from '../lib/supabase'4import { Button, Input } from '@rneui/themed'56// Tells Supabase Auth to continuously refresh the session automatically if7// the app is in the foreground. When this is added, you will continue to receive8// `onAuthStateChange` events with the `TOKEN_REFRESHED` or `SIGNED_OUT` event9// if the user's session is terminated. This should only be registered once.10AppState.addEventListener('change', (state) => {11 if (state === 'active') {12 supabase.auth.startAutoRefresh()13 } else {14 supabase.auth.stopAutoRefresh()15 }16})1718export default function Auth() {19 const [email, setEmail] = useState('')20 const [password, setPassword] = useState('')21 const [loading, setLoading] = useState(false)2223 async function signInWithEmail() {24 setLoading(true)25 const { error } = await supabase.auth.signInWithPassword({26 email: email,27 password: password,28 })2930 if (error) Alert.alert(error.message)31 setLoading(false)32 }3334 async function signUpWithEmail() {35 setLoading(true)36 const {37 data: { session },38 error,39 } = await supabase.auth.signUp({40 email: email,41 password: password,42 })4344 if (error) Alert.alert(error.message)45 if (!session) Alert.alert('Please check your inbox for email verification!')46 setLoading(false)47 }4849 return (50 <View style={styles.container}>51 <View style={[styles.verticallySpaced, styles.mt20]}>52 <Input53 label="Email"54 leftIcon={{ type: 'font-awesome', name: 'envelope' }}55 onChangeText={(text) => setEmail(text)}56 value={email}57 placeholder="email@address.com"58 autoCapitalize={'none'}59 />60 </View>61 <View style={styles.verticallySpaced}>62 <Input63 label="Password"64 leftIcon={{ type: 'font-awesome', name: 'lock' }}65 onChangeText={(text) => setPassword(text)}66 value={password}67 secureTextEntry={true}68 placeholder="Password"69 autoCapitalize={'none'}70 />71 </View>72 <View style={[styles.verticallySpaced, styles.mt20]}>73 <Button title="Sign in" disabled={loading} onPress={() => signInWithEmail()} />74 </View>75 <View style={styles.verticallySpaced}>76 <Button title="Sign up" disabled={loading} onPress={() => signUpWithEmail()} />77 </View>78 </View>79 )80}8182const styles = StyleSheet.create({83 container: {84 marginTop: 40,85 padding: 12,86 },87 verticallySpaced: {88 paddingTop: 4,89 paddingBottom: 4,90 alignSelf: 'stretch',91 },92 mt20: {93 marginTop: 20,94 },95})By default Supabase Auth requires email verification before a session is created for the users. To support email verification you need to implement deep link handling!
While testing, you can disable email confirmation in your project's email auth provider settings.
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.
1import { useState, useEffect } from 'react'2import { supabase } from '../lib/supabase'3import { StyleSheet, View, Alert } from 'react-native'4import { Button, Input } from '@rneui/themed'5import { Session } from '@supabase/supabase-js'67export default function Account({ session }: { session: Session }) {8 const [loading, setLoading] = useState(true)9 const [username, setUsername] = useState('')10 const [website, setWebsite] = useState('')11 const [avatarUrl, setAvatarUrl] = useState('')1213 useEffect(() => {14 if (session) getProfile()15 }, [session])1617 async function getProfile() {18 try {19 setLoading(true)20 if (!session?.user) throw new Error('No user on the session!')2122 const { data, error, status } = await supabase23 .from('profiles')24 .select(`username, website, avatar_url`)25 .eq('id', session?.user.id)26 .single()27 if (error && status !== 406) {28 throw error29 }3031 if (data) {32 setUsername(data.username)33 setWebsite(data.website)34 setAvatarUrl(data.avatar_url)35 }36 } catch (error) {37 if (error instanceof Error) {38 Alert.alert(error.message)39 }40 } finally {41 setLoading(false)42 }43 }4445 async function updateProfile({46 username,47 website,48 avatar_url,49 }: {50 username: string51 website: string52 avatar_url: string53 }) {54 try {55 setLoading(true)56 if (!session?.user) throw new Error('No user on the session!')5758 const updates = {59 id: session?.user.id,60 username,61 website,62 avatar_url,63 updated_at: new Date(),64 }6566 const { error } = await supabase.from('profiles').upsert(updates)6768 if (error) {69 throw error70 }71 } catch (error) {72 if (error instanceof Error) {73 Alert.alert(error.message)74 }75 } finally {76 setLoading(false)77 }78 }7980 return (81 <View style={styles.container}>82 <View style={[styles.verticallySpaced, styles.mt20]}>83 <Input label="Email" value={session?.user?.email} disabled />84 </View>85 <View style={styles.verticallySpaced}>86 <Input label="Username" value={username || ''} onChangeText={(text) => setUsername(text)} />87 </View>88 <View style={styles.verticallySpaced}>89 <Input label="Website" value={website || ''} onChangeText={(text) => setWebsite(text)} />90 </View>9192 <View style={[styles.verticallySpaced, styles.mt20]}>93 <Button94 title={loading ? 'Loading ...' : 'Update'}95 onPress={() => updateProfile({ username, website, avatar_url: avatarUrl })}96 disabled={loading}97 />98 </View>99100 <View style={styles.verticallySpaced}>101 <Button title="Sign Out" onPress={() => supabase.auth.signOut()} />102 </View>103 </View>104 )105}106107const styles = StyleSheet.create({108 container: {109 marginTop: 40,110 padding: 12,111 },112 verticallySpaced: {113 paddingTop: 4,114 paddingBottom: 4,115 alignSelf: 'stretch',116 },117 mt20: {118 marginTop: 20,119 },120})Launch!
Now that we have all the components in place, let's update App.tsx:
1import { useState, useEffect } from 'react'2import { supabase } from './lib/supabase'3import Auth from './components/Auth'4import Account from './components/Account'5import { View } from 'react-native'6import { Session } from '@supabase/supabase-js'78export default function App() {9 const [session, setSession] = useState<Session | null>(null)1011 useEffect(() => {12 supabase.auth.getSession().then(({ data: { session } }) => {13 setSession(session)14 })1516 supabase.auth.onAuthStateChange((_event, session) => {17 setSession(session)18 })19 }, [])2021 return (22 <View>23 {session && session.user ? <Account key={session.user.id} session={session} /> : <Auth />}24 </View>25 )26}Once that's done, run this in a terminal window:
1npm startAnd 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 an image picker that works on the environment you will build the project for, we will use expo-image-picker in this example.
1npx expo install expo-image-pickerCreate 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:
1import { useState, useEffect } from 'react'2import { supabase } from '../lib/supabase'3import { StyleSheet, View, Alert, Image, Button } from 'react-native'4import * as ImagePicker from 'expo-image-picker'56interface Props {7 size: number8 url: string | null9 onUpload: (filePath: string) => void10}1112export default function Avatar({ url, size = 150, onUpload }: Props) {13 const [uploading, setUploading] = useState(false)14 const [avatarUrl, setAvatarUrl] = useState<string | null>(null)15 const avatarSize = { height: size, width: size }1617 useEffect(() => {18 if (url) downloadImage(url)19 }, [url])2021 async function downloadImage(path: string) {22 try {23 const { data, error } = await supabase.storage.from('avatars').download(path)2425 if (error) {26 throw error27 }2829 const fr = new FileReader()30 fr.readAsDataURL(data)31 fr.onload = () => {32 setAvatarUrl(fr.result as string)33 }34 } catch (error) {35 if (error instanceof Error) {36 console.log('Error downloading image: ', error.message)37 }38 }39 }4041 async function uploadAvatar() {42 try {43 setUploading(true)4445 const result = await ImagePicker.launchImageLibraryAsync({46 mediaTypes: ImagePicker.MediaTypeOptions.Images, // Restrict to only images47 allowsMultipleSelection: false, // Can only select one image48 allowsEditing: true, // Allows the user to crop / rotate their photo before uploading it49 quality: 1,50 exif: false, // We don't want nor need that data.51 })5253 if (result.canceled || !result.assets || result.assets.length === 0) {54 console.log('User cancelled image picker.')55 return56 }5758 const image = result.assets[0]59 console.log('Got image', image)6061 if (!image.uri) {62 throw new Error('No image uri!') // Realistically, this should never happen, but just in case...63 }6465 const arraybuffer = await fetch(image.uri).then((res) => res.arrayBuffer())6667 const fileExt = image.uri?.split('.').pop()?.toLowerCase() ?? 'jpeg'68 const path = `${Date.now()}.${fileExt}`69 const { data, error: uploadError } = await supabase.storage70 .from('avatars')71 .upload(path, arraybuffer, {72 contentType: image.mimeType ?? 'image/jpeg',73 })7475 if (uploadError) {76 throw uploadError77 }7879 onUpload(data.path)80 } catch (error) {81 if (error instanceof Error) {82 Alert.alert(error.message)83 } else {84 throw error85 }86 } finally {87 setUploading(false)88 }89 }9091 return (92 <View>93 {avatarUrl ? (94 <Image95 source={{ uri: avatarUrl }}96 accessibilityLabel="Avatar"97 style={[avatarSize, styles.avatar, styles.image]}98 />99 ) : (100 <View style={[avatarSize, styles.avatar, styles.noImage]} />101 )}102 <View>103 <Button104 title={uploading ? 'Uploading ...' : 'Upload'}105 onPress={uploadAvatar}106 disabled={uploading}107 />108 </View>109 </View>110 )111}112113const styles = StyleSheet.create({114 avatar: {115 borderRadius: 5,116 overflow: 'hidden',117 maxWidth: '100%',118 },119 image: {120 objectFit: 'cover',121 paddingTop: 0,122 },123 noImage: {124 backgroundColor: '#333',125 borderWidth: 1,126 borderStyle: 'solid',127 borderColor: 'rgb(200, 200, 200)',128 borderRadius: 5,129 },130})Add the new widget
And then we can add the widget to the Account page:
1// Import the new component2import Avatar from './Avatar'34// ...5return (6 <View>7 {/* Add to the body */}8 <View>9 <Avatar10 size={200}11 url={avatarUrl}12 onUpload={(url: string) => {13 setAvatarUrl(url)14 updateProfile({ username, website, avatar_url: url })15 }}16 />17 </View>18 {/* ... */}19 </View>20)21// ...Now you will need to run the prebuild command to get the application working on your chosen platform.
1npx expo prebuildAt this stage you have a fully functional application!