Build a User Management App with Ionic React
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 app from scratch.
Initialize an Ionic React app
We can use the Ionic CLI to initialize
an app called supabase-ionic-react:
1npm install -g @ionic/cli2ionic start supabase-ionic-react blank --type react3cd supabase-ionic-reactThen let's install the only additional dependency: supabase-js
1npm install @supabase/supabase-jsAnd finally we want to save the environment variables in a .env.
All we need are the API URL and the key that you copied earlier.
1VITE_SUPABASE_URL=YOUR_SUPABASE_URL2VITE_SUPABASE_PUBLISHABLE_KEY=YOUR_SUPABASE_PUBLISHABLE_KEYNow that we have the API credentials in place, let's create a helper file to initialize the Supabase client. These variables will be exposed on the browser, and that's completely fine since we have Row Level Security enabled on our Database.
1import { createClient } from '@supabase/supabase-js'23const supabaseUrl = import.meta.env.VITE_SUPABASE_URL || ''4const supabasePublishableKey = import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY || ''56export const supabase = createClient(supabaseUrl, supabasePublishableKey)Set up a login route
Let's set up a React component to manage logins and sign ups. We'll use Magic Links, so users can sign in with their email without using passwords.
1import { useState } from 'react';2import {3 IonButton,4 IonContent,5 IonHeader,6 IonInput,7 IonItem,8 IonLabel,9 IonList,10 IonPage,11 IonTitle,12 IonToolbar,13 useIonToast,14 useIonLoading,15} from '@ionic/react';1617import {supabase} from '../supabaseClient'1819export function LoginPage() {20 const [email, setEmail] = useState('');2122 const [showLoading, hideLoading] = useIonLoading();23 const [showToast ] = useIonToast();24 const handleLogin = async (e: React.FormEvent<HTMLFormElement>) => {25 console.log()26 e.preventDefault();27 await showLoading();28 try {29 await supabase.auth.signInWithOtp({30 "email": email31 });32 await showToast({ message: 'Check your email for the login link!' });33 } catch (e: any) {34 await showToast({ message: e.error_description || e.message , duration: 5000});35 } finally {36 await hideLoading();37 }38 };39 return (40 <IonPage>41 <IonHeader>42 <IonToolbar>43 <IonTitle>Login</IonTitle>44 </IonToolbar>45 </IonHeader>4647 <IonContent>48 <div className="ion-padding">49 <h1>Supabase + Ionic React</h1>50 <p>Sign in via magic link with your email below</p>51 </div>52 <IonList inset={true}>53 <form onSubmit={handleLogin}>54 <IonItem>55 <IonLabel position="stacked">Email</IonLabel>56 <IonInput57 value={email}58 name="email"59 onIonChange={(e) => setEmail(e.detail.value ?? '')}60 type="email"61 ></IonInput>62 </IonItem>63 <div className="ion-text-center">64 <IonButton type="submit" fill="clear">65 Login66 </IonButton>67 </div>68 </form>69 </IonList>70 </IonContent>71 </IonPage>72 );73}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 {2 IonButton,3 IonContent,4 IonHeader,5 IonInput,6 IonItem,7 IonLabel,8 IonPage,9 IonTitle,10 IonToolbar,11 useIonLoading,12 useIonToast,13 useIonRouter14} from '@ionic/react';15import { useEffect, useState } from 'react';16import { supabase } from '../supabaseClient';17import { Session } from '@supabase/supabase-js';1819export function AccountPage() {20 const [showLoading, hideLoading] = useIonLoading();21 const [showToast] = useIonToast();22 const [session, setSession] = useState<Session | null>(null)23 const router = useIonRouter();24 const [profile, setProfile] = useState({25 username: '',26 website: '',27 avatar_url: '',28 });2930 useEffect(() => {31 const getSession = async () => {32 setSession(await supabase.auth.getSession().then((res) => res.data.session))33 }34 getSession()35 supabase.auth.onAuthStateChange((_event, session) => {36 setSession(session)37 })38 }, [])3940 useEffect(() => {41 getProfile();42 }, [session]);43 const getProfile = async () => {44 console.log('get');45 await showLoading();46 try {47 const user = await supabase.auth.getUser();48 const { data, error, status } = await supabase49 .from('profiles')50 .select(`username, website, avatar_url`)51 .eq('id', user!.data.user?.id)52 .single();5354 if (error && status !== 406) {55 throw error;56 }5758 if (data) {59 setProfile({60 username: data.username,61 website: data.website,62 avatar_url: data.avatar_url,63 });64 }65 } catch (error: any) {66 showToast({ message: error.message, duration: 5000 });67 } finally {68 await hideLoading();69 }70 };71 const signOut = async () => {72 await supabase.auth.signOut();73 router.push('/', 'forward', 'replace');74 }75 const updateProfile = async (e?: any, avatar_url: string = '') => {76 e?.preventDefault();7778 console.log('update ');79 await showLoading();8081 try {82 const user = await supabase.auth.getUser();8384 const updates = {85 id: user!.data.user?.id,86 ...profile,87 avatar_url: avatar_url,88 updated_at: new Date(),89 };9091 const { error } = await supabase.from('profiles').upsert(updates);9293 if (error) {94 throw error;95 }96 } catch (error: any) {97 showToast({ message: error.message, duration: 5000 });98 } finally {99 await hideLoading();100 }101 };102 return (103 <IonPage>104 <IonHeader>105 <IonToolbar>106 <IonTitle>Account</IonTitle>107 </IonToolbar>108 </IonHeader>109110 <IonContent>111 <form onSubmit={updateProfile}>112 <IonItem>113 <IonLabel>114 <p>Email</p>115 <p>{session?.user?.email}</p>116 </IonLabel>117 </IonItem>118119 <IonItem>120 <IonLabel position="stacked">Name</IonLabel>121 <IonInput122 type="text"123 name="username"124 value={profile.username}125 onIonChange={(e) =>126 setProfile({ ...profile, username: e.detail.value ?? '' })127 }128 ></IonInput>129 </IonItem>130131 <IonItem>132 <IonLabel position="stacked">Website</IonLabel>133 <IonInput134 type="url"135 name="website"136 value={profile.website}137 onIonChange={(e) =>138 setProfile({ ...profile, website: e.detail.value ?? '' })139 }140 ></IonInput>141 </IonItem>142 <div className="ion-text-center">143 <IonButton fill="clear" type="submit">144 Update Profile145 </IonButton>146 </div>147 </form>148149 <div className="ion-text-center">150 <IonButton fill="clear" onClick={signOut}>151 Log Out152 </IonButton>153 </div>154 </IonContent>155 </IonPage>156 );157}Launch!
Now that we have all the components in place, let's update App.tsx:
1import { Redirect, Route } from 'react-router-dom'2import { IonApp, IonRouterOutlet, setupIonicReact } from '@ionic/react'3import { IonReactRouter } from '@ionic/react-router'4import { supabase } from './supabaseClient'56import '@ionic/react/css/ionic.bundle.css'78/* Theme variables */9import './theme/variables.css'10import { LoginPage } from './pages/Login'11import { AccountPage } from './pages/Account'12import { useEffect, useState } from 'react'13import { Session } from '@supabase/supabase-js'1415setupIonicReact()1617const App: React.FC = () => {18 const [session, setSession] = useState<Session | null>(null)19 useEffect(() => {20 const getSession = async () => {21 setSession(await supabase.auth.getSession().then((res) => res.data.session))22 }23 getSession()24 supabase.auth.onAuthStateChange((_event, session) => {25 setSession(session)26 })27 }, [])28 return (29 <IonApp>30 <IonReactRouter>31 <IonRouterOutlet>32 <Route33 exact34 path="/"35 render={() => {36 return session ? <Redirect to="/account" /> : <LoginPage />37 }}38 />39 <Route exact path="/account">40 <AccountPage />41 </Route>42 </IonRouterOutlet>43 </IonReactRouter>44 </IonApp>45 )46}4748export default AppOnce that's done, run this in a terminal window:
1ionic serveAnd then open the browser to localhost:3000 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.
Create an upload widget
First install two packages in order to interact with the user's camera.
1npm install @ionic/pwa-elements @capacitor/cameraCapacitor is a cross platform native runtime from Ionic that enables web apps to be deployed through the app store and provides access to native device API.
Ionic PWA elements is a companion package that will polyfill certain browser APIs that provide no user interface with custom Ionic UI.
With those packages installed we can update our index.tsx to include an additional bootstrapping call for the Ionic PWA Elements.
1import React from 'react'2import ReactDOM from 'react-dom'3import App from './App'4import * as serviceWorkerRegistration from './serviceWorkerRegistration'5import reportWebVitals from './reportWebVitals'67import { defineCustomElements } from '@ionic/pwa-elements/loader'8defineCustomElements(window)910ReactDOM.render(11 <React.StrictMode>12 <App />13 </React.StrictMode>,14 document.getElementById('root')15)1617serviceWorkerRegistration.unregister()18reportWebVitals()Then create an AvatarComponent.
1import { IonIcon } from '@ionic/react';2import { person } from 'ionicons/icons';3import { Camera, CameraResultType } from '@capacitor/camera';4import { useEffect, useState } from 'react';5import { supabase } from '../supabaseClient';6import './Avatar.css'7export function Avatar({8 url,9 onUpload,10}: {11 url: string;12 onUpload: (e: any, file: string) => Promise<void>;13}) {14 const [avatarUrl, setAvatarUrl] = useState<string | undefined>();1516 useEffect(() => {17 if (url) {18 downloadImage(url);19 }20 }, [url]);21 const uploadAvatar = async () => {22 try {23 const photo = await Camera.getPhoto({24 resultType: CameraResultType.DataUrl,25 });2627 const file = await fetch(photo.dataUrl!)28 .then((res) => res.blob())29 .then(30 (blob) =>31 new File([blob], 'my-file', { type: `image/${photo.format}` })32 );3334 const fileName = `${Math.random()}-${new Date().getTime()}.${35 photo.format36 }`;37 const { error: uploadError } = await supabase.storage38 .from('avatars')39 .upload(fileName, file);40 if (uploadError) {41 throw uploadError;42 }43 onUpload(null, fileName);44 } catch (error) {45 console.log(error);46 }47 };4849 const downloadImage = async (path: string) => {50 try {51 const { data, error } = await supabase.storage52 .from('avatars')53 .download(path);54 if (error) {55 throw error;56 }57 const url = URL.createObjectURL(data!);58 setAvatarUrl(url);59 } catch (error: any) {60 console.log('Error downloading image: ', error.message);61 }62 };6364 return (65 <div className="avatar">66 <div className="avatar_wrapper" onClick={uploadAvatar}>67 {avatarUrl ? (68 <img src={avatarUrl} />69 ) : (70 <IonIcon icon={person} className="no-avatar" />71 )}72 </div>7374 </div>75 );76}Add the new widget
And then we can add the widget to the Account page:
1// Import the new component23import { Avatar } from '../components/Avatar';45// ...6return (7 <IonPage>8 <IonHeader>9 <IonToolbar>10 <IonTitle>Account</IonTitle>11 </IonToolbar>12 </IonHeader>1314 <IonContent>15 <Avatar url={profile.avatar_url} onUpload={updateProfile}></Avatar>At this stage you have a fully functional application!