Build a User Management App with Refine
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.
About Refine
Refine is a React-based framework used to rapidly build data-heavy applications like admin panels, dashboards, storefronts and any type of CRUD apps. It separates app concerns into individual layers, each backed by a React context and respective provider object. For example, the auth layer represents a context served by a specific set of authProvider methods that carry out authentication and authorization actions such as logging in, logging out, getting roles data, etc. Similarly, the data layer offers another level of abstraction that is equipped with dataProvider methods to handle CRUD operations at appropriate backend API endpoints.
Refine provides hassle-free integration with Supabase backend with its supplementary @refinedev/supabase package. It generates authProvider and dataProvider methods at project initialization, so we don't need to expend much effort to define them ourselves. We just need to choose Supabase as our backend service while creating the app with create refine-app.
It is possible to customize the authProvider for Supabase and as we'll see below, it can be tweaked from src/authProvider.ts file. In contrast, the Supabase dataProvider is part of node_modules and therefore is not subject to modification.
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 Refine app from scratch.
Initialize a Refine app
We can use create refine-app command to initialize an app. Run the following in the terminal:
1npm create refine-app@latest -- --preset refine-supabaseIn the above command, we are using the refine-supabase preset which chooses the Supabase supplementary package for our app. We are not using any UI framework, so we'll have a headless UI with plain React and CSS styling.
The refine-supabase preset installs the @refinedev/supabase package which out-of-the-box includes the Supabase dependency: supabase-js.
We also need to install @refinedev/react-hook-form and react-hook-form packages that allow us to use React Hook Form inside Refine apps. Run:
1npm install @refinedev/react-hook-form react-hook-formWith the app initialized and packages installed, at this point before we begin discussing Refine concepts, let's try running the app:
1cd app-name2npm run devWe should have a running instance of the app with a Welcome page at http://localhost:5173.
Let's move ahead to understand the generated code now.
Refine supabaseClient
The create refine-app generated a Supabase client for us in the src/utility/supabaseClient.ts file. It has two constants: SUPABASE_URL and SUPABASE_KEY. We want to replace them as supabaseUrl and supabasePublishableKey respectively and assign them our own Supabase server's values.
We'll update it with environment variables managed by Vite:
1import { createClient } from '@refinedev/supabase'23const supabaseUrl = import.meta.env.VITE_SUPABASE_URL4const supabasePublishableKey = import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY56export const supabaseClient = createClient(supabaseUrl, supabasePublishableKey, {7 db: {8 schema: 'public',9 },10 auth: {11 persistSession: true,12 },13})And then, we want to save the environment variables in a .env.local file. All you need are the API URL and the key that you copied earlier.
1VITE_SUPABASE_URL=YOUR_SUPABASE_URL2VITE_SUPABASE_PUBLISHABLE_KEY=YOUR_SUPABASE_PUBLISHABLE_KEYThe supabaseClient will be used in fetch calls to Supabase endpoints from our app. As we'll see below, the client is instrumental in implementing authentication using Refine's auth provider methods and CRUD actions with appropriate data provider methods.
One optional step is to update the CSS file src/App.css to make the app look nice.
You can find the full contents of this file here.
In order for us to add login and user profile pages in this App, we have to tweak the <Refine /> component inside App.tsx.
The <Refine /> component
The App.tsx file initially looks like this:
1import { Refine, WelcomePage } from '@refinedev/core'2import { RefineKbar, RefineKbarProvider } from '@refinedev/kbar'3import routerProvider, {4 DocumentTitleHandler,5 UnsavedChangesNotifier,6} from '@refinedev/react-router'7import { dataProvider, liveProvider } from '@refinedev/supabase'8import { BrowserRouter, Route, Routes } from 'react-router'9import './App.css'10import authProvider from './authProvider'11import { supabaseClient } from './utility'1213function App() {14 return (15 <BrowserRouter>16 <RefineKbarProvider>17 <Refine18 dataProvider={dataProvider(supabaseClient)}19 liveProvider={liveProvider(supabaseClient)}20 authProvider={authProvider}21 routerProvider={routerProvider}22 options={{23 syncWithLocation: true,24 warnWhenUnsavedChanges: true,25 }}26 >27 <Routes>28 <Route index element={<WelcomePage />} />29 </Routes>30 <RefineKbar />31 <UnsavedChangesNotifier />32 <DocumentTitleHandler />33 </Refine>34 </RefineKbarProvider>35 </BrowserRouter>36 )37}3839export default AppWe'd like to focus on the <Refine /> component, which comes with several props passed to it. Notice the dataProvider prop. It uses a dataProvider() function with supabaseClient passed as argument to generate the data provider object. The authProvider object also uses supabaseClient in implementing its methods. You can look it up in src/authProvider.ts file.
Customize authProvider
If you examine the authProvider object you can notice that it has a login method that implements a OAuth and Email / Password strategy for authentication. We'll, however, remove them and use Magic Links to allow users sign in with their email without using passwords.
We want to use supabaseClient auth's signInWithOtp method inside authProvider.login method:
src/authProvider.ts
1login: async ({ email }) => {2 try {3 const { error } = await supabaseClient.auth.signInWithOtp({ email });45 if (!error) {6 alert("Check your email for the login link!");7 return {8 success: true,9 };10 };1112 throw error;13 } catch (e: any) {14 alert(e.message);15 return {16 success: false,17 e,18 };19 }20},We also want to remove register, updatePassword, forgotPassword and getPermissions properties, which are optional type members and also not necessary for our app. The final authProvider object looks like this:
1import { AuthProvider } from '@refinedev/core'23import { supabaseClient } from './utility'45const authProvider: AuthProvider = {6 login: async ({ email }) => {7 try {8 const { error } = await supabaseClient.auth.signInWithOtp({ email })910 if (!error) {11 alert('Check your email for the login link!')12 return {13 success: true,14 }15 }1617 throw error18 } catch (e: any) {19 alert(e.message)20 return {21 success: false,22 e,23 }24 }25 },26 logout: async () => {27 const { error } = await supabaseClient.auth.signOut()2829 if (error) {30 return {31 success: false,32 error,33 }34 }3536 return {37 success: true,38 redirectTo: '/',39 }40 },41 onError: async (error) => {42 console.error(error)43 return { error }44 },45 check: async () => {46 try {47 const { data } = await supabaseClient.auth.getSession()48 const { session } = data4950 if (!session) {51 return {52 authenticated: false,53 error: {54 message: 'Check failed',55 name: 'Session not found',56 },57 logout: true,58 redirectTo: '/login',59 }60 }61 } catch (error: any) {62 return {63 authenticated: false,64 error: error || {65 message: 'Check failed',66 name: 'Not authenticated',67 },68 logout: true,69 redirectTo: '/login',70 }71 }7273 return {74 authenticated: true,75 }76 },77 getIdentity: async () => {78 const { data } = await supabaseClient.auth.getUser()7980 if (data?.user) {81 return {82 ...data.user,83 name: data.user.email,84 }85 }8687 return null88 },89}9091export default authProviderSet up a login component
We have chosen to use the headless Refine core package that comes with no supported UI framework. So, let's set up a plain React component to manage logins and sign ups.
Create and edit src/components/auth.tsx:
1import { useState } from 'react'2import { useLogin } from '@refinedev/core'34export default function Auth() {5 const [email, setEmail] = useState('')6 const { isPending, mutate: login } = useLogin()78 const handleLogin = async (event: { preventDefault: () => void }) => {9 event.preventDefault()10 login({ email })11 }1213 return (14 <div className="row flex flex-center container">15 <div className="col-6 form-widget">16 <h1 className="header">Supabase + Refine</h1>17 <p className="description">Sign in via magic link with your email below</p>18 <form className="form-widget" onSubmit={handleLogin}>19 <div>20 <input21 className="inputField"22 type="email"23 placeholder="Your email"24 value={email}25 required={true}26 onChange={(e) => setEmail(e.target.value)}27 />28 </div>29 <div>30 <button className={'button block'} disabled={isPending}>31 {isPending ? <span>Loading</span> : <span>Send magic link</span>}32 </button>33 </div>34 </form>35 </div>36 </div>37 )38}Notice we are using the useLogin() Refine auth hook to grab the mutate: login method to use inside handleLogin() function and isLoading state for our form submission. The useLogin() hook conveniently offers us access to authProvider.login method for authenticating the user with OTP.
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 in src/components/account.tsx.
1import { BaseKey, useGetIdentity, useLogout } from '@refinedev/core'2import { useForm } from '@refinedev/react-hook-form'34interface IUserIdentity {5 id?: BaseKey6 username: string7 name: string8}910export interface IProfile {11 id?: string12 username?: string13 website?: string14 avatar_url?: string15}1617export default function Account() {18 const { data: userIdentity } = useGetIdentity<IUserIdentity>()1920 const { mutate: logOut } = useLogout()2122 const {23 refineCore: { formLoading, query, onFinish },24 register,25 control,26 handleSubmit,27 } = useForm<IProfile>({28 refineCoreProps: {29 resource: 'profiles',30 action: 'edit',31 id: userIdentity?.id,32 redirect: false,33 onMutationError: (data) => alert(data?.message),34 },35 })3637 return (38 <div className="container" style={{ padding: '50px 0 100px 0' }}>39 <form onSubmit={handleSubmit(onFinish)} className="form-widget">40 <div>41 <label htmlFor="email">Email</label>42 <input id="email" name="email" type="text" value={userIdentity?.name} disabled />43 </div>44 <div>45 <label htmlFor="username">Name</label>46 <input id="username" type="text" {...register('username')} />47 </div>48 <div>49 <label htmlFor="website">Website</label>50 <input id="website" type="url" {...register('website')} />51 </div>5253 <div>54 <button className="button block primary" type="submit" disabled={formLoading}>55 {formLoading ? 'Loading ...' : 'Update'}56 </button>57 </div>5859 <div>60 <button className="button block" type="button" onClick={() => logOut()}>61 Sign Out62 </button>63 </div>64 </form>65 </div>66 )67}Notice above that, we are using three Refine hooks, namely the useGetIdentity(), useLogOut() and useForm() hooks.
useGetIdentity() is a auth hook that gets the identity of the authenticated user. It grabs the current user by invoking the authProvider.getIdentity method under the hood.
useLogOut() is also an auth hook. It calls the authProvider.logout method to end the session.
useForm(), in contrast, is a data hook that exposes a series of useful objects that serve the edit form. For example, we are grabbing the onFinish function to submit the form with the handleSubmit event handler. We are also using formLoading property to present state changes of the submitted form.
The useForm() hook is a higher-level hook built on top of Refine's useForm() core hook. It fully supports form state management, field validation and submission using React Hook Form. Behind the scenes, it invokes the dataProvider.getOne method to get the user profile data from our Supabase /profiles endpoint and also invokes dataProvider.update method when onFinish() is called.
Launch!
Now that we have all the components in place, let's define the routes for the pages in which they should be rendered.
Add the routes for /login with the <Auth /> component and the routes for index path with the <Account /> component. So, the final App.tsx:
1import { Authenticated, Refine } from '@refinedev/core'2import { RefineKbar, RefineKbarProvider } from '@refinedev/kbar'3import routerProvider, {4 CatchAllNavigate,5 DocumentTitleHandler,6 UnsavedChangesNotifier,7} from '@refinedev/react-router'8import { dataProvider, liveProvider } from '@refinedev/supabase'9import { BrowserRouter, Outlet, Route, Routes } from 'react-router'1011import './App.css'12import authProvider from './authProvider'13import { supabaseClient } from './utility'14import Account from './components/account'15import Auth from './components/auth'1617function App() {18 return (19 <BrowserRouter>20 <RefineKbarProvider>21 <Refine22 dataProvider={dataProvider(supabaseClient)}23 liveProvider={liveProvider(supabaseClient)}24 authProvider={authProvider}25 routerProvider={routerProvider}26 options={{27 syncWithLocation: true,28 warnWhenUnsavedChanges: true,29 }}30 >31 <Routes>32 <Route33 element={34 <Authenticated35 key="authenticated-routes"36 fallback={<CatchAllNavigate to="/login" />}37 >38 <Outlet />39 </Authenticated>40 }41 >42 <Route index element={<Account />} />43 </Route>44 <Route element={<Authenticated key="auth-pages" fallback={<Outlet />} />}>45 <Route path="/login" element={<Auth />} />46 </Route>47 </Routes>48 <RefineKbar />49 <UnsavedChangesNotifier />50 <DocumentTitleHandler />51 </Refine>52 </RefineKbarProvider>53 </BrowserRouter>54 )55}5657export default AppLet's test the App by running the server again:
1npm run devAnd then open the browser to localhost:5173 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
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/components/avatar.tsx:
1import { useEffect, useState } from 'react'2import { supabaseClient } from '../utility/supabaseClient'34type TAvatarProps = {5 url?: string6 size: number7 onUpload: (filePath: string) => void8}910export default function Avatar({ url, size, onUpload }: TAvatarProps) {11 const [avatarUrl, setAvatarUrl] = useState('')12 const [uploading, setUploading] = useState(false)1314 useEffect(() => {15 if (url) downloadImage(url)16 }, [url])1718 async function downloadImage(path: string) {19 try {20 const { data, error } = await supabaseClient.storage.from('avatars').download(path)21 if (error) {22 throw error23 }24 const url = URL.createObjectURL(data)25 setAvatarUrl(url)26 } catch (error: any) {27 console.log('Error downloading image: ', error?.message)28 }29 }3031 async function uploadAvatar(event: React.ChangeEvent<HTMLInputElement>) {32 try {33 setUploading(true)3435 if (!event.target.files || event.target.files.length === 0) {36 throw new Error('You must select an image to upload.')37 }3839 const file = event.target.files[0]40 const fileExt = file.name.split('.').pop()41 const fileName = `${Math.random()}.${fileExt}`42 const filePath = `${fileName}`4344 const { error: uploadError } = await supabaseClient.storage45 .from('avatars')46 .upload(filePath, file)4748 if (uploadError) {49 throw uploadError50 }51 onUpload(filePath)52 } catch (error: any) {53 alert(error.message)54 } finally {55 setUploading(false)56 }57 }5859 return (60 <div>61 {avatarUrl ? (62 <img63 src={avatarUrl}64 alt="Avatar"65 className="avatar image"66 style={{ height: size, width: size }}67 />68 ) : (69 <div className="avatar no-image" style={{ height: size, width: size }} />70 )}71 <div style={{ width: size }}>72 <label className="button primary block" htmlFor="single">73 {uploading ? 'Uploading ...' : 'Upload'}74 </label>75 <input76 style={{77 visibility: 'hidden',78 position: 'absolute',79 }}80 type="file"81 id="single"82 name="avatar_url"83 accept="image/*"84 onChange={uploadAvatar}85 disabled={uploading}86 />87 </div>88 </div>89 )90}Add the new widget
And then we can add the widget to the Account page at src/components/account.tsx:
1// Import the new components2import { Controller } from 'react-hook-form'3import Avatar from './avatar'45// ...67return (8 <div className="container" style={{ padding: '50px 0 100px 0' }}>9 <form onSubmit={handleSubmit} className="form-widget">10 <Controller11 control={control}12 name="avatar_url"13 render={({ field }) => {14 return (15 <Avatar16 url={field.value}17 size={150}18 onUpload={(filePath) => {19 onFinish({20 ...query?.data?.data,21 avatar_url: filePath,22 onMutationError: (data: { message: string }) => alert(data?.message),23 })24 field.onChange({25 target: {26 value: filePath,27 },28 })29 }}30 />31 )32 }}33 />34 {/* ... */}35 </form>36 </div>37)At this stage, you have a fully functional application!