Getting Started

Build a User Management App with RedwoodJS


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

About RedwoodJS

A Redwood application is split into two parts: a frontend and a backend. This is represented as two node projects within a single monorepo.

The frontend project is called web and the backend project is called api. For clarity, we will refer to these in prose as "sides," that is, the web side and the api side. They are separate projects because code on the web side will end up running in the user's browser while code on the api side will run on a server somewhere.

The api side is an implementation of a GraphQL API. The business logic is organized into "services" that represent their own internal API and can be called both from external GraphQL requests and other internal services.

The web side is built with React. Redwood's router makes it simple to map URL paths to React "Page" components (and automatically code-split your app on each route). Pages may contain a "Layout" component to wrap content. They also contain "Cells" and regular React components. Cells allow you to declaratively manage the lifecycle of a component that fetches and displays data.

For the sake of consistency with the other framework tutorials, we'll build this app a little differently than normal. We won't use Prisma to connect to the Supabase Postgres database or Prisma migrations as one typically might in a Redwood app. Instead, we'll rely on the Supabase client to do some of the work on the web side and use the client again on the api side to do data fetching as well.

That means you will want to refrain from running any yarn rw prisma migrate commands and also double check your build commands on deployment to ensure Prisma won't reset your database. Prisma currently doesn't support cross-schema foreign keys, so introspecting the schema fails due to how your Supabase public schema references the auth.users.

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 RedwoodJS app from scratch.

Make sure you have installed yarn since RedwoodJS relies on it to manage its packages in workspaces for its web and api "sides."

Initialize a RedwoodJS app

We can use Create Redwood App command to initialize an app called supabase-redwoodjs:


_10
yarn create redwood-app supabase-redwoodjs
_10
cd supabase-redwoodjs

While the app is installing, you should see:


_10
✔ Creating Redwood app
_10
✔ Checking node and yarn compatibility
_10
✔ Creating directory 'supabase-redwoodjs'
_10
✔ Installing packages
_10
✔ Running 'yarn install'... (This could take a while)
_10
✔ Convert TypeScript files to JavaScript
_10
✔ Generating types
_10
_10
Thanks for trying out Redwood!

Then let's install the only additional dependency supabase-js by running the setup auth command:


_10
yarn redwood setup auth supabase

When prompted:

Overwrite existing /api/src/lib/auth.[jt]s?

Say, yes and it will setup the Supabase client in your app and also provide hooks used with Supabase authentication.


_10
✔ Generating auth lib...
_10
✔ Successfully wrote file `./api/src/lib/auth.js`
_10
✔ Adding auth config to web...
_10
✔ Adding auth config to GraphQL API...
_10
✔ Adding required web packages...
_10
✔ Installing packages...
_10
✔ One more thing...
_10
_10
You will need to add your Supabase URL (SUPABASE_URL), public API KEY,
_10
and JWT SECRET (SUPABASE_KEY, and SUPABASE_JWT_SECRET) to your .env file.

Next, we want to save the environment variables in a .env. We need the API URL as well as the anon and jwt_secret keys that you copied earlier.

.env

_10
SUPABASE_URL=YOUR_SUPABASE_URL
_10
SUPABASE_KEY=YOUR_SUPABASE_ANON_KEY
_10
SUPABASE_JWT_SECRET=YOUR_SUPABASE_JWT_SECRET

And finally, you will also need to save just the web side environment variables to the redwood.toml.

redwood.toml

_10
[web]
_10
title = "Supabase Redwood Tutorial"
_10
port = 8910
_10
apiProxyPath = "/.redwood/functions"
_10
includeEnvironmentVariables = ["SUPABASE_URL", "SUPABASE_KEY"]
_10
[api]
_10
port = 8911
_10
[browser]
_10
open = true

These variables will be exposed on the browser, and that's completely fine. They allow your web app to initialize the Supabase client with your public anon key since we have Row Level Security enabled on our Database.

You'll see these being used to configure your Supabase client in web/src/App.js:

web/src/App.js

_21
// ... Redwood imports
_21
import { AuthProvider } from '@redwoodjs/auth'
_21
import { createClient } from '@supabase/supabase-js'
_21
_21
// ...
_21
_21
const supabase = createClient(process.env.SUPABASE_URL, process.env.SUPABASE_KEY)
_21
_21
const App = () => (
_21
<FatalErrorBoundary page={FatalErrorPage}>
_21
<RedwoodProvider titleTemplate="%PageTitle | %AppTitle">
_21
<AuthProvider client={supabase} type="supabase">
_21
<RedwoodApolloProvider>
_21
<Routes />
_21
</RedwoodApolloProvider>
_21
</AuthProvider>
_21
</RedwoodProvider>
_21
</FatalErrorBoundary>
_21
)
_21
_21
export default App

App styling (optional)

An optional step is to update the CSS file web/src/index.css to make the app look nice. You can find the full contents of this file here.

Start RedwoodJS and your first page

Let's test our setup at the moment by starting up the app:


_10
yarn rw dev

You should see a "Welcome to RedwoodJS" page and a message about not having any pages yet.

So, let's create a "home" page:


_10
yarn rw generate page home /
_10
_10
✔ Generating page files...
_10
✔ Successfully wrote file `./web/src/pages/HomePage/HomePage.stories.js`
_10
✔ Successfully wrote file `./web/src/pages/HomePage/HomePage.test.js`
_10
✔ Successfully wrote file `./web/src/pages/HomePage/HomePage.js`
_10
✔ Updating routes file...
_10
✔ Generating types ...

You can stop the dev server if you want; to see your changes, just be sure to run yarn rw dev again.

You should see the Home page route in web/src/Routes.js:

web/src/Routes.js

_12
import { Router, Route } from '@redwoodjs/router'
_12
_12
const Routes = () => {
_12
return (
_12
<Router>
_12
<Route path="/" page={HomePage} name="home" />
_12
<Route notfound page={NotFoundPage} />
_12
</Router>
_12
)
_12
}
_12
_12
export default Routes

Set up a login component

Let's set up a Redwood component to manage logins and sign ups. We'll use Magic Links, so users can sign in with their email without using passwords.


_10
yarn rw g component auth
_10
_10
✔ Generating component files...
_10
✔ Successfully wrote file `./web/src/components/Auth/Auth.test.js`
_10
✔ Successfully wrote file `./web/src/components/Auth/Auth.stories.js`
_10
✔ Successfully wrote file `./web/src/components/Auth/Auth.js`

Now, update the Auth.js component to contain:

/web/src/components/Auth/Auth.js

_53
import { useState } from 'react'
_53
import { useAuth } from '@redwoodjs/auth'
_53
_53
const Auth = () => {
_53
const { logIn } = useAuth()
_53
const [loading, setLoading] = useState(false)
_53
const [email, setEmail] = useState('')
_53
_53
const handleLogin = async (email) => {
_53
try {
_53
setLoading(true)
_53
const { error } = await logIn({ email })
_53
if (error) throw error
_53
alert('Check your email for the login link!')
_53
} catch (error) {
_53
alert(error.error_description || error.message)
_53
} finally {
_53
setLoading(false)
_53
}
_53
}
_53
_53
return (
_53
<div className="row flex-center flex">
_53
<div className="col-6 form-widget">
_53
<h1 className="header">Supabase + RedwoodJS</h1>
_53
<p className="description">Sign in via magic link with your email below</p>
_53
<div>
_53
<input
_53
className="inputField"
_53
type="email"
_53
placeholder="Your email"
_53
value={email}
_53
onChange={(e) => setEmail(e.target.value)}
_53
/>
_53
</div>
_53
<div>
_53
<button
_53
onClick={(e) => {
_53
e.preventDefault()
_53
handleLogin(email)
_53
}}
_53
className={'button block'}
_53
disabled={loading}
_53
>
_53
{loading ? <span>Loading</span> : <span>Send magic link</span>}
_53
</button>
_53
</div>
_53
</div>
_53
</div>
_53
)
_53
}
_53
_53
export default Auth

Set up an account component

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


_10
yarn rw g component account
_10
_10
✔ Generating component files...
_10
✔ Successfully wrote file `./web/src/components/Account/Account.test.js`
_10
✔ Successfully wrote file `./web/src/components/Account/Account.stories.js`
_10
✔ Successfully wrote file `./web/src/components/Account/Account.js`

And then update the file to contain:

web/src/components/Account/Account.js

_121
import { useState, useEffect } from 'react'
_121
import { useAuth } from '@redwoodjs/auth'
_121
_121
const Account = () => {
_121
const { client: supabase, currentUser, logOut } = useAuth()
_121
const [loading, setLoading] = useState(true)
_121
const [username, setUsername] = useState(null)
_121
const [website, setWebsite] = useState(null)
_121
const [avatar_url, setAvatarUrl] = useState(null)
_121
_121
useEffect(() => {
_121
getProfile()
_121
}, [supabase.auth.session])
_121
_121
async function getProfile() {
_121
try {
_121
setLoading(true)
_121
const user = supabase.auth.user()
_121
_121
const { data, error, status } = await supabase
_121
.from('profiles')
_121
.select(`username, website, avatar_url`)
_121
.eq('id', user.id)
_121
.single()
_121
_121
if (error && status !== 406) {
_121
throw error
_121
}
_121
_121
if (data) {
_121
setUsername(data.username)
_121
setWebsite(data.website)
_121
setAvatarUrl(data.avatar_url)
_121
}
_121
} catch (error) {
_121
alert(error.message)
_121
} finally {
_121
setLoading(false)
_121
}
_121
}
_121
_121
async function updateProfile({ username, website, avatar_url }) {
_121
try {
_121
setLoading(true)
_121
const user = supabase.auth.user()
_121
_121
const updates = {
_121
id: user.id,
_121
username,
_121
website,
_121
avatar_url,
_121
updated_at: new Date(),
_121
}
_121
_121
const { error } = await supabase.from('profiles').upsert(updates, {
_121
returning: 'minimal', // Don't return the value after inserting
_121
})
_121
_121
if (error) {
_121
throw error
_121
}
_121
_121
alert('Updated profile!')
_121
} catch (error) {
_121
alert(error.message)
_121
} finally {
_121
setLoading(false)
_121
}
_121
}
_121
_121
return (
_121
<div className="row flex-center flex">
_121
<div className="col-6 form-widget">
_121
<h1 className="header">Supabase + RedwoodJS</h1>
_121
<p className="description">Your profile</p>
_121
<div className="form-widget">
_121
<div>
_121
<label htmlFor="email">Email</label>
_121
<input id="email" type="text" value={currentUser.email} disabled />
_121
</div>
_121
<div>
_121
<label htmlFor="username">Name</label>
_121
<input
_121
id="username"
_121
type="text"
_121
value={username || ''}
_121
onChange={(e) => setUsername(e.target.value)}
_121
/>
_121
</div>
_121
<div>
_121
<label htmlFor="website">Website</label>
_121
<input
_121
id="website"
_121
type="url"
_121
value={website || ''}
_121
onChange={(e) => setWebsite(e.target.value)}
_121
/>
_121
</div>
_121
_121
<div>
_121
<button
_121
className="button primary block"
_121
onClick={() => updateProfile({ username, website, avatar_url })}
_121
disabled={loading}
_121
>
_121
{loading ? 'Loading ...' : 'Update'}
_121
</button>
_121
</div>
_121
_121
<div>
_121
<button className="button block" onClick={() => logOut()}>
_121
Sign Out
_121
</button>
_121
</div>
_121
</div>
_121
</div>
_121
</div>
_121
)
_121
}
_121
_121
export default Account

You'll see the use of useAuth() several times. Redwood's useAuth hook provides convenient ways to access logIn, logOut, currentUser, and access the supabase authenticate client. We'll use it to get an instance of the supabase client to interact with your API.

Update home page

Now that we have all the components in place, let's update your HomePage page to use them:

web/src/pages/HomePage/HomePage.js

_18
import { useAuth } from '@redwoodjs/auth'
_18
import { MetaTags } from '@redwoodjs/web'
_18
_18
import Account from 'src/components/Account'
_18
import Auth from 'src/components/Auth'
_18
_18
const HomePage = () => {
_18
const { isAuthenticated } = useAuth()
_18
_18
return (
_18
<>
_18
<MetaTags title="Welcome" />
_18
{!isAuthenticated ? <Auth /> : <Account />}
_18
</>
_18
)
_18
}
_18
_18
export default HomePage

Launch!

Once that's done, run this in a terminal window to launch the dev server:


_10
yarn rw dev

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

Supabase RedwoodJS

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:


_10
yarn rw g component avatar
_10
✔ Generating component files...
_10
✔ Successfully wrote file `./web/src/components/Avatar/Avatar.test.js`
_10
✔ Successfully wrote file `./web/src/components/Avatar/Avatar.stories.js`
_10
✔ Successfully wrote file `./web/src/components/Avatar/Avatar.js`

Now, update your Avatar component to contain the following widget:

web/src/components/Avatar/Avatar.js

_86
import { useEffect, useState } from 'react'
_86
import { useAuth } from '@redwoodjs/auth'
_86
_86
const Avatar = ({ url, size, onUpload }) => {
_86
const { client: supabase } = useAuth()
_86
_86
const [avatarUrl, setAvatarUrl] = useState(null)
_86
const [uploading, setUploading] = useState(false)
_86
_86
useEffect(() => {
_86
if (url) downloadImage(url)
_86
}, [url])
_86
_86
async function downloadImage(path) {
_86
try {
_86
const { data, error } = await supabase.storage.from('avatars').download(path)
_86
if (error) {
_86
throw error
_86
}
_86
const url = URL.createObjectURL(data)
_86
setAvatarUrl(url)
_86
} catch (error) {
_86
console.log('Error downloading image: ', error.message)
_86
}
_86
}
_86
_86
async function uploadAvatar(event) {
_86
try {
_86
setUploading(true)
_86
_86
if (!event.target.files || event.target.files.length === 0) {
_86
throw new Error('You must select an image to upload.')
_86
}
_86
_86
const file = event.target.files[0]
_86
const fileExt = file.name.split('.').pop()
_86
const fileName = `${Math.random()}.${fileExt}`
_86
const filePath = `${fileName}`
_86
_86
const { error: uploadError } = await supabase.storage.from('avatars').upload(filePath, file)
_86
_86
if (uploadError) {
_86
throw uploadError
_86
}
_86
_86
onUpload(filePath)
_86
} catch (error) {
_86
alert(error.message)
_86
} finally {
_86
setUploading(false)
_86
}
_86
}
_86
_86
return (
_86
<div>
_86
{avatarUrl ? (
_86
<img
_86
src={avatarUrl}
_86
alt="Avatar"
_86
className="avatar image"
_86
style={{ height: size, width: size }}
_86
/>
_86
) : (
_86
<div className="avatar no-image" style={{ height: size, width: size }} />
_86
)}
_86
<div style={{ width: size }}>
_86
<label className="button primary block" htmlFor="single">
_86
{uploading ? 'Uploading ...' : 'Upload'}
_86
</label>
_86
<input
_86
style={{
_86
visibility: 'hidden',
_86
position: 'absolute',
_86
}}
_86
type="file"
_86
id="single"
_86
accept="image/*"
_86
onChange={uploadAvatar}
_86
disabled={uploading}
_86
/>
_86
</div>
_86
</div>
_86
)
_86
}
_86
_86
export default Avatar

Add the new widget

And then we can add the widget to the Account component:

web/src/components/Account/Account.js

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

At this stage you have a fully functional application!

See also