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

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

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!