Getting Started

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 User Management example

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.

_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: avatarUrl,
_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
</form>
_18
)

At this stage you have a fully functional application!