Home

Build a User Management App with 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 - 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.

note

You can easily pull the database schema down to your local project by running the db pull command. Read the local development docs for detailed instructions.


_10
supabase link --project-ref <project-id>
_10
# You can get <project-id> from your project's dashboard URL: https://supabase.com/dashboard/project/<project-id>
_10
supabase db pull

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 app from scratch.

Initialize a React app#

We can use Vite to initialize an app called supabase-react:


_10
npm create vite@latest supabase-react -- --template react
_10
cd supabase-react

Then let's install the only additional dependency: supabase-js.


_10
npm install @supabase/supabase-js

And finally we want to save the environment variables in a .env.local file. All we need are the API URL and the anon key that you copied earlier.

.env

_10
VITE_SUPABASE_URL=YOUR_SUPABASE_URL
_10
VITE_SUPABASE_ANON_KEY=YOUR_SUPABASE_ANON_KEY

Now 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.

Create and edit src/supabaseClient.js:

src/supabaseClient.js

_10
import { createClient } from '@supabase/supabase-js'
_10
_10
const supabaseUrl = import.meta.env.VITE_SUPABASE_URL
_10
const supabaseAnonKey = import.meta.env.VITE_SUPABASE_ANON_KEY
_10
_10
export const supabase = createClient(supabaseUrl, supabaseAnonKey)

App Styling (Optional)#

An optional step is to update the CSS file src/index.css to make the app look nice. You can find the full contents of this file here.

Set up a Login component#

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.

Create and edit src/Auth.jsx:

src/Auth.jsx

_47
import { useState } from 'react'
_47
import { supabase } from './supabaseClient'
_47
_47
export default function Auth() {
_47
const [loading, setLoading] = useState(false)
_47
const [email, setEmail] = useState('')
_47
_47
const handleLogin = async (event) => {
_47
event.preventDefault()
_47
_47
setLoading(true)
_47
const { error } = await supabase.auth.signInWithOtp({ email })
_47
_47
if (error) {
_47
alert(error.error_description || error.message)
_47
} else {
_47
alert('Check your email for the login link!')
_47
}
_47
setLoading(false)
_47
}
_47
_47
return (
_47
<div className="row flex flex-center">
_47
<div className="col-6 form-widget">
_47
<h1 className="header">Supabase + React</h1>
_47
<p className="description">Sign in via magic link with your email below</p>
_47
<form className="form-widget" onSubmit={handleLogin}>
_47
<div>
_47
<input
_47
className="inputField"
_47
type="email"
_47
placeholder="Your email"
_47
value={email}
_47
required={true}
_47
onChange={(e) => setEmail(e.target.value)}
_47
/>
_47
</div>
_47
<div>
_47
<button className={'button block'} disabled={loading}>
_47
{loading ? <span>Loading</span> : <span>Send magic link</span>}
_47
</button>
_47
</div>
_47
</form>
_47
</div>
_47
</div>
_47
)
_47
}

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 src/Account.jsx.

src/Account.jsx

_98
import { useState, useEffect } from 'react'
_98
import { supabase } from './supabaseClient'
_98
_98
export default function Account({ session }) {
_98
const [loading, setLoading] = useState(true)
_98
const [username, setUsername] = useState(null)
_98
const [website, setWebsite] = useState(null)
_98
const [avatar_url, setAvatarUrl] = useState(null)
_98
_98
useEffect(() => {
_98
async function getProfile() {
_98
setLoading(true)
_98
const { user } = session
_98
_98
const { data, error } = await supabase
_98
.from('profiles')
_98
.select(`username, website, avatar_url`)
_98
.eq('id', user.id)
_98
.single()
_98
_98
if (error) {
_98
console.warn(error)
_98
} else if (data) {
_98
setUsername(data.username)
_98
setWebsite(data.website)
_98
setAvatarUrl(data.avatar_url)
_98
}
_98
_98
setLoading(false)
_98
}
_98
_98
getProfile()
_98
}, [session])
_98
_98
async function updateProfile(event, avatarUrl) {
_98
event.preventDefault()
_98
_98
setLoading(true)
_98
const { user } = session
_98
_98
const updates = {
_98
id: user.id,
_98
username,
_98
website,
_98
avatar_url,
_98
updated_at: new Date(),
_98
}
_98
_98
const { error } = await supabase.from('profiles').upsert(updates)
_98
_98
if (error) {
_98
alert(error.message)
_98
} else {
_98
setAvatarUrl(avatarUrl)
_98
}
_98
setLoading(false)
_98
}
_98
_98
return (
_98
<form onSubmit={updateProfile} className="form-widget">
_98
<div>
_98
<label htmlFor="email">Email</label>
_98
<input id="email" type="text" value={session.user.email} disabled />
_98
</div>
_98
<div>
_98
<label htmlFor="username">Name</label>
_98
<input
_98
id="username"
_98
type="text"
_98
required
_98
value={username || ''}
_98
onChange={(e) => setUsername(e.target.value)}
_98
/>
_98
</div>
_98
<div>
_98
<label htmlFor="website">Website</label>
_98
<input
_98
id="website"
_98
type="url"
_98
value={website || ''}
_98
onChange={(e) => setWebsite(e.target.value)}
_98
/>
_98
</div>
_98
_98
<div>
_98
<button className="button block primary" type="submit" disabled={loading}>
_98
{loading ? 'Loading ...' : 'Update'}
_98
</button>
_98
</div>
_98
_98
<div>
_98
<button className="button block" type="button" onClick={() => supabase.auth.signOut()}>
_98
Sign Out
_98
</button>
_98
</div>
_98
</form>
_98
)
_98
}

Launch!#

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

src/App.jsx

_27
import './App.css'
_27
import { useState, useEffect } from 'react'
_27
import { supabase } from './supabaseClient'
_27
import Auth from './Auth'
_27
import Account from './Account'
_27
_27
function App() {
_27
const [session, setSession] = useState(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
<div className="container" style={{ padding: '50px 0 100px 0' }}>
_27
{!session ? <Auth /> : <Account key={session.user.id} session={session} />}
_27
</div>
_27
)
_27
}
_27
_27
export default App

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


_10
npm run dev

And then open the browser to localhost:5173 and you should see the completed app.

Supabase React

Bonus: Profile photos#

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

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:

Create and edit src/Avatar.jsx:

src/Avatar.jsx

_82
import { useEffect, useState } from 'react'
_82
import { supabase } from './supabaseClient'
_82
_82
export default function Avatar({ url, size, onUpload }) {
_82
const [avatarUrl, setAvatarUrl] = useState(null)
_82
const [uploading, setUploading] = useState(false)
_82
_82
useEffect(() => {
_82
if (url) downloadImage(url)
_82
}, [url])
_82
_82
async function downloadImage(path) {
_82
try {
_82
const { data, error } = await supabase.storage.from('avatars').download(path)
_82
if (error) {
_82
throw error
_82
}
_82
const url = URL.createObjectURL(data)
_82
setAvatarUrl(url)
_82
} catch (error) {
_82
console.log('Error downloading image: ', error.message)
_82
}
_82
}
_82
_82
async function uploadAvatar(event) {
_82
try {
_82
setUploading(true)
_82
_82
if (!event.target.files || event.target.files.length === 0) {
_82
throw new Error('You must select an image to upload.')
_82
}
_82
_82
const file = event.target.files[0]
_82
const fileExt = file.name.split('.').pop()
_82
const fileName = `${Math.random()}.${fileExt}`
_82
const filePath = `${fileName}`
_82
_82
const { error: uploadError } = await supabase.storage.from('avatars').upload(filePath, file)
_82
_82
if (uploadError) {
_82
throw uploadError
_82
}
_82
_82
onUpload(event, filePath)
_82
} catch (error) {
_82
alert(error.message)
_82
} finally {
_82
setUploading(false)
_82
}
_82
}
_82
_82
return (
_82
<div>
_82
{avatarUrl ? (
_82
<img
_82
src={avatarUrl}
_82
alt="Avatar"
_82
className="avatar image"
_82
style={{ height: size, width: size }}
_82
/>
_82
) : (
_82
<div className="avatar no-image" style={{ height: size, width: size }} />
_82
)}
_82
<div style={{ width: size }}>
_82
<label className="button primary block" htmlFor="single">
_82
{uploading ? 'Uploading ...' : 'Upload'}
_82
</label>
_82
<input
_82
style={{
_82
visibility: 'hidden',
_82
position: 'absolute',
_82
}}
_82
type="file"
_82
id="single"
_82
accept="image/*"
_82
onChange={uploadAvatar}
_82
disabled={uploading}
_82
/>
_82
</div>
_82
</div>
_82
)
_82
}

Add the new widget#

And then we can add the widget to the Account page at src/Account.jsx:

src/Account.jsx

_18
// Import the new component
_18
import Avatar from './Avatar'
_18
_18
// ...
_18
_18
return (
_18
<form onSubmit={updateProfile} className="form-widget">
_18
{/* Add to the body */}
_18
<Avatar
_18
url={avatar_url}
_18
size={150}
_18
onUpload={(event, url) => {
_18
updateProfile(event, url)
_18
}}
_18
/>
_18
{/* ... */}
_18
</div>
_18
)

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:


_32
create or replace function delete_old_avatar()
_32
returns trigger
_32
language 'plpgsql'
_32
security definer
_32
as $$
_32
declare
_32
status int;
_32
content text;
_32
avatar_name text;
_32
begin
_32
if coalesce(old.avatar_url, '') <> ''
_32
and (tg_op = 'DELETE' or (old.avatar_url <> new.avatar_url)) then
_32
-- extract avatar name
_32
avatar_name := old.avatar_url;
_32
select
_32
into status, content
_32
result.status, result.content
_32
from public.delete_avatar(avatar_name) as result;
_32
if status <> 200 then
_32
raise warning 'Could not delete avatar: % %', status, content;
_32
end if;
_32
end if;
_32
if tg_op = 'DELETE' then
_32
return old;
_32
end if;
_32
return new;
_32
end;
_32
$$;
_32
_32
create trigger before_profile_changes
_32
before update of avatar_url or delete on public.profiles
_32
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!