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.

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)

And one 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

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

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
let { 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

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

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!