Getting Started

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

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 equipped with dataProvider methods to handle CRUD operations at appropriate backend API endpoints.

Refine provides hassle-free integration with a Supabase backend with its supplementary @refinedev/supabase package. It generates authProvider and dataProvider methods at project initialization, so you don't need to spend much effort defining them yourself, choose Supabase as the backend service while creating the app with create refine-app.

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#

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

  1. Go to the SQL Editor page in the Dashboard.
  2. Click User Management Starter under the Community > Quickstarts tab.
  3. Click Run.

Get 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 from the project Connect dialog.

Read the API keys docs for a full explanation of all key types and their uses.

Building the app#

Start building the Refine app from scratch.

Initialize a Refine app#

Use create refine-app command to initialize an app. Run the following in the terminal:

1
npm create refine-app@latest -- --preset refine-supabase

The command above uses the refine-supabase preset which chooses the Supabase supplementary package for the app. There's no UI framework, so the app has 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.

Install the @refinedev/react-hook-form and react-hook-form packages that to use React Hook Form inside Refine apps. Run:

1
npm install @refinedev/react-hook-form react-hook-form

Refine supabaseClient#

The create refine-app generated a Supabase client in the src/utility/supabaseClient.ts file. It has two constants: SUPABASE_URL and SUPABASE_KEY. Replace them as supabaseUrl and supabasePublishableKey respectively and assign them your Supabase server's values.

Update it with environment variables managed by Vite:

src/utility/supabaseClient.ts
1
import { createClient } from "@refinedev/supabase";
2
3
const supabaseUrl = import.meta.env.VITE_SUPABASE_URL;
4
const supabaseKey = import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY;
5
6
export const supabaseClient = createClient(supabaseUrl, supabaseKey, {
7
db: {
8
schema: "public",
9
},
10
auth: {
11
persistSession: true,
12
},
13
});
View source

Save the environment variables in a .env.local file. All you need are the API URL and the key that you copied earlier.

1
VITE_SUPABASE_URL=YOUR_SUPABASE_URL
2
VITE_SUPABASE_PUBLISHABLE_KEY=YOUR_SUPABASE_PUBLISHABLE_KEY

The supabaseClient fetches calls to Supabase endpoints from the app. 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 to add login and user profile pages in this App, tweak the <Refine /> component inside App.tsx.

The <Refine /> component#

The App.tsx file initially looks like this:

1
import { Refine, WelcomePage } from '@refinedev/core'
2
import { RefineKbar, RefineKbarProvider } from '@refinedev/kbar'
3
import routerProvider, {
4
DocumentTitleHandler,
5
UnsavedChangesNotifier,
6
} from '@refinedev/react-router'
7
import { dataProvider, liveProvider } from '@refinedev/supabase'
8
import { BrowserRouter, Route, Routes } from 'react-router'
9
import './App.css'
10
import authProvider from './authProvider'
11
import { supabaseClient } from './utility'
12
13
function App() {
14
return (
15
<BrowserRouter>
16
<RefineKbarProvider>
17
<Refine
18
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
}
38
39
export default App

Focus on the <Refine /> component, which comes with 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 an OAuth and Email / Password strategy for authentication. This tutorial instead removes them and use Magic Links to allow users sign in with their email without using passwords.

Use supabaseClient auth's signInWithOtp method inside authProvider.login method:

src/authProvider.ts
1
login: async ({ email }) => {
2
try {
3
const { error } = await supabaseClient.auth.signInWithOtp({ email });
4
5
if (!error) {
6
alert("Check your email for the login link!");
7
return {
8
success: true,
9
};
10
};
11
12
throw error;
13
} catch (e: any) {
14
alert(e.message);
15
return {
16
success: false,
17
e,
18
};
19
}
20
},

Remove register, updatePassword, forgotPassword and getPermissions properties, which are optional type members and also not necessary for the app. The final authProvider object looks like this:

src/authProvider.ts
1
import { AuthProvider } from "@refinedev/core";
2
3
import { supabaseClient } from "./utility";
4
5
const authProvider: AuthProvider = {
6
login: async ({ email }) => {
7
try {
8
const { error } = await supabaseClient.auth.signInWithOtp({ email });
9
10
if (!error) {
11
alert("Check your email for the login link!");
12
return {
13
success: true,
14
};
15
}
16
17
throw error;
18
} 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();
28
29
if (error) {
30
return {
31
success: false,
32
error,
33
};
34
}
35
36
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, error } = await supabaseClient.auth.getClaims();
48
49
if (error || !data) {
50
return {
51
authenticated: false,
52
error: {
53
message: "Check failed",
54
name: "Session not found",
55
},
56
logout: true,
57
redirectTo: "/login",
58
};
59
}
60
} catch (error: any) {
61
return {
62
authenticated: false,
63
error: error || {
64
message: "Check failed",
65
name: "Not authenticated",
66
},
67
logout: true,
68
redirectTo: "/login",
69
};
70
}
71
72
return {
73
authenticated: true,
74
};
75
},
76
getIdentity: async () => {
77
const { data } = await supabaseClient.auth.getUser();
78
79
if (data?.user) {
80
return {
81
...data.user,
82
name: data.user.email,
83
};
84
}
85
86
return null;
87
},
88
};
89
90
export default authProvider;
View source

Set up a login component#

As the app uses the headless Refine core package that comes with no supported UI framework set up a plain React component to manage logins and sign ups.

Create and edit src/components/auth.tsx:

src/components/auth.tsx
1
import { useState } from "react";
2
3
import { useLogin } from "@refinedev/core";
4
5
export default function Auth() {
6
const [email, setEmail] = useState("");
7
const { isPending, mutate: login } = useLogin();
8
9
const handleLogin = async (event: { preventDefault: () => void }) => {
10
event.preventDefault();
11
login({ email });
12
};
13
14
return (
15
<div className="row flex flex-center container">
16
<div className="col-6 form-widget">
17
<h1 className="header">Supabase + Refine</h1>
18
<p className="description">
19
Sign in via magic link with your email below
20
</p>
21
<form className="form-widget" onSubmit={handleLogin}>
22
<div>
23
<input
24
className="inputField"
25
type="email"
26
placeholder="Your email"
27
value={email}
28
required={true}
29
onChange={(e) => setEmail(e.target.value)}
30
/>
31
</div>
32
<div>
33
<button className={"button block"} disabled={isPending}>
34
{isPending ? <span>Loading</span> : <span>Send magic link</span>}
35
</button>
36
</div>
37
</form>
38
</div>
39
</div>
40
);
41
}
View source

The useLogin() Refine auth hook to grab the mutate: login method to use inside handleLogin() function and isLoading state for the form submission. The useLogin() hook conveniently offers access to authProvider.login method for authenticating the user with OTP.

Account page#

After a user is signed in, allow them to edit their profile details and manage their account.

Create a new component for that in src/components/account.tsx.

src/components/account.tsx
1
import { BaseKey, useGetIdentity, useLogout } from "@refinedev/core";
2
3
import { useForm } from "@refinedev/react-hook-form";
4
5
// ...
6
7
interface IUserIdentity {
8
id?: BaseKey;
9
username: string;
10
name: string;
11
}
12
13
export interface IProfile {
14
id?: string;
15
username?: string;
16
website?: string;
17
avatar_url?: string;
18
}
19
20
export default function Account() {
21
const { data: userIdentity } = useGetIdentity<IUserIdentity>();
22
23
const { mutate: logOut } = useLogout();
24
25
const {
26
refineCore: { formLoading, query, onFinish },
27
register,
28
control,
29
handleSubmit,
30
} = useForm<IProfile>({
31
refineCoreProps: {
32
resource: "profiles",
33
action: "edit",
34
id: userIdentity?.id,
35
redirect: false,
36
onMutationError: (data) => alert(data?.message),
37
},
38
});
39
40
return (
41
<div className="container" style={{ padding: "50px 0 100px 0" }}>
42
<form onSubmit={handleSubmit(onFinish)} className="form-widget">
43
44
{/* ... */}
45
46
<div>
47
<label htmlFor="email">Email</label>
48
<input
49
id="email"
50
name="email"
51
type="text"
52
value={userIdentity?.name}
53
disabled
54
/>
55
</div>
56
<div>
57
<label htmlFor="username">Name</label>
58
<input id="username" type="text" {...register("username")} />
59
</div>
60
<div>
61
<label htmlFor="website">Website</label>
62
<input id="website" type="url" {...register("website")} />
63
</div>
64
65
<div>
66
<button
67
className="button block primary"
68
type="submit"
69
disabled={formLoading}
70
>
71
{formLoading ? "Loading ..." : "Update"}
72
</button>
73
</div>
74
75
<div>
76
<button
77
className="button block"
78
type="button"
79
onClick={() => logOut()}
80
>
81
Sign Out
82
</button>
83
</div>
84
</form>
85
</div>
86
);
87
}
View source

This uses 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, grabbing the onFinish function to submit the form with the handleSubmit event handler. It also uses 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 the Supabase /profiles endpoint and also invokes dataProvider.update method when onFinish() is called.

Launch!#

Now that you have all the components in place, 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:

src/App.tsx
1
import { Authenticated, Refine } from "@refinedev/core";
2
import { RefineKbar, RefineKbarProvider } from "@refinedev/kbar";
3
import routerProvider, {
4
CatchAllNavigate,
5
DocumentTitleHandler,
6
UnsavedChangesNotifier,
7
} from "@refinedev/react-router";
8
import { BrowserRouter, Outlet, Route, Routes } from "react-router";
9
10
import { dataProvider, liveProvider } from "@refinedev/supabase";
11
import authProvider from "./authProvider";
12
import { supabaseClient } from "./utility";
13
14
import Account from "./components/account";
15
import Auth from "./components/auth";
16
17
import "./App.css";
18
19
function App() {
20
return (
21
<BrowserRouter>
22
<RefineKbarProvider>
23
<Refine
24
dataProvider={dataProvider(supabaseClient)}
25
liveProvider={liveProvider(supabaseClient)}
26
authProvider={authProvider}
27
routerProvider={routerProvider}
28
options={{
29
syncWithLocation: true,
30
warnWhenUnsavedChanges: true,
31
}}
32
>
33
<Routes>
34
<Route
35
element={
36
<Authenticated
37
key="authenticated-routes"
38
fallback={<CatchAllNavigate to="/login" />}
39
>
40
<Outlet />
41
</Authenticated>
42
}
43
>
44
<Route index element={<Account />} />
45
</Route>
46
<Route
47
element={<Authenticated key="auth-pages" fallback={<Outlet />} />}
48
>
49
<Route path="/login" element={<Auth />} />
50
</Route>
51
</Routes>
52
<RefineKbar />
53
<UnsavedChangesNotifier />
54
<DocumentTitleHandler />
55
</Refine>
56
</RefineKbarProvider>
57
</BrowserRouter>
58
);
59
}
60
61
export default App;
View source

Test the App by running the server again:

1
npm run dev

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

Supabase Refine

Bonus: Profile photos#

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

Create an upload widget#

Create an avatar for the user so that they can upload a profile photo. Add a new component:

Create and edit src/components/avatar.tsx:

src/components/avatar.tsx
1
import { useEffect, useState } from "react";
2
3
import { supabaseClient } from "../utility/supabaseClient";
4
5
type TAvatarProps = {
6
url?: string;
7
size: number;
8
onUpload: (filePath: string) => void;
9
};
10
11
export default function Avatar({ url, size, onUpload }: TAvatarProps) {
12
const [avatarUrl, setAvatarUrl] = useState("");
13
const [uploading, setUploading] = useState(false);
14
15
useEffect(() => {
16
if (url) downloadImage(url);
17
}, [url]);
18
19
async function downloadImage(path: string) {
20
try {
21
const { data, error } = await supabaseClient.storage
22
.from("avatars")
23
.download(path);
24
if (error) {
25
throw error;
26
}
27
const url = URL.createObjectURL(data);
28
setAvatarUrl(url);
29
} catch (error: any) {
30
console.log("Error downloading image: ", error?.message);
31
}
32
}
33
34
async function uploadAvatar(event: React.ChangeEvent<HTMLInputElement>) {
35
try {
36
setUploading(true);
37
38
if (!event.target.files || event.target.files.length === 0) {
39
throw new Error("You must select an image to upload.");
40
}
41
42
const file = event.target.files[0];
43
const fileExt = file.name.split(".").pop();
44
const fileName = `${Math.random()}.${fileExt}`;
45
const filePath = `${fileName}`;
46
47
const { error: uploadError } = await supabaseClient.storage
48
.from("avatars")
49
.upload(filePath, file);
50
51
if (uploadError) {
52
throw uploadError;
53
}
54
onUpload(filePath);
55
} catch (error: any) {
56
alert(error.message);
57
} finally {
58
setUploading(false);
59
}
60
}
61
62
return (
63
<div>
64
{avatarUrl ? (
65
<img
66
src={avatarUrl}
67
alt="Avatar"
68
className="avatar image"
69
style={{ height: size, width: size }}
70
/>
71
) : (
72
<div
73
className="avatar no-image"
74
style={{ height: size, width: size }}
75
/>
76
)}
77
<div style={{ width: size }}>
78
<label className="button primary block" htmlFor="single">
79
{uploading ? "Uploading ..." : "Upload"}
80
</label>
81
<input
82
style={{
83
visibility: "hidden",
84
position: "absolute",
85
}}
86
type="file"
87
id="single"
88
name="avatar_url"
89
accept="image/*"
90
onChange={uploadAvatar}
91
disabled={uploading}
92
/>
93
</div>
94
</div>
95
);
96
}
View source

Add the new widget#

And then add the widget to the Account page at src/components/account.tsx:

src/components/account.tsx
1
import { BaseKey, useGetIdentity, useLogout } from "@refinedev/core";
2
3
import { useForm } from "@refinedev/react-hook-form";
4
import { Controller } from "react-hook-form";
5
6
import Avatar from "./avatar";
7
8
interface IUserIdentity {
9
id?: BaseKey;
10
username: string;
11
name: string;
12
}
13
14
export interface IProfile {
15
id?: string;
16
username?: string;
17
website?: string;
18
avatar_url?: string;
19
}
20
21
export default function Account() {
22
const { data: userIdentity } = useGetIdentity<IUserIdentity>();
23
24
const { mutate: logOut } = useLogout();
25
26
const {
27
refineCore: { formLoading, query, onFinish },
28
register,
29
control,
30
handleSubmit,
31
} = useForm<IProfile>({
32
refineCoreProps: {
33
resource: "profiles",
34
action: "edit",
35
id: userIdentity?.id,
36
redirect: false,
37
onMutationError: (data) => alert(data?.message),
38
},
39
});
40
41
return (
42
<div className="container" style={{ padding: "50px 0 100px 0" }}>
43
<form onSubmit={handleSubmit(onFinish)} className="form-widget">
44
<Controller
45
control={control}
46
name="avatar_url"
47
render={({ field }) => {
48
return (
49
<Avatar
50
url={field.value}
51
size={150}
52
onUpload={(filePath) => {
53
onFinish({
54
...query?.data?.data,
55
avatar_url: filePath,
56
onMutationError: (data: { message: string }) =>
57
alert(data?.message),
58
});
59
field.onChange({
60
target: {
61
value: filePath,
62
},
63
});
64
}}
65
/>
66
);
67
}}
68
/>
69
<div>
70
<label htmlFor="email">Email</label>
71
<input
72
id="email"
73
name="email"
74
type="text"
75
value={userIdentity?.name}
76
disabled
77
/>
78
</div>
79
<div>
80
<label htmlFor="username">Name</label>
81
<input id="username" type="text" {...register("username")} />
82
</div>
83
<div>
84
<label htmlFor="website">Website</label>
85
<input id="website" type="url" {...register("website")} />
86
</div>
87
88
<div>
89
<button
90
className="button block primary"
91
type="submit"
92
disabled={formLoading}
93
>
94
{formLoading ? "Loading ..." : "Update"}
95
</button>
96
</div>
97
98
<div>
99
<button
100
className="button block"
101
type="button"
102
onClick={() => logOut()}
103
>
104
Sign Out
105
</button>
106
</div>
107
</form>
108
</div>
109
);
110
}
View source

At this stage, you have a fully functional application!