Quickstart: React

Intro#

This example provides the steps to build a basic user management app. It includes:

  • Supabase Database: a Postgres database for storing your user data.
  • Supabase Auth: users can sign in with magic links (no passwords, only email).
  • Supabase Storage: users can upload a photo.
  • Row Level Security: data is protected so that individuals can only access their own data.
  • Instant APIs: APIs will be automatically generated when you create your database tables.

By the end of this guide you'll have an app which allows users to login and update some basic profile details:

Supabase User Management example

GitHub#

Should you get stuck while working through the guide, refer to this repo.

Project set up#

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. Go to app.supabase.com.
  2. Click on "New Project".
  3. Enter your project details.
  4. 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 URL and anon key from the API settings.

  1. Go to the Settings page in the Dashboard.
  2. Click API in the sidebar.
  3. Find your API 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 Create React App to initialize an app called supabase-react:

npx create-react-app supabase-react
cd supabase-react

Then let's install the only additional dependency: supabase-js.

npm install @supabase/supabase-js

And finally we want to save the environment variables in a .env. All we need are the API URL and the anon key that you copied earlier.

.env
REACT_APP_SUPABASE_URL=YOUR_SUPABASE_URL
REACT_APP_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.

src/supabaseClient.js
1import { createClient } from '@supabase/supabase-js'
2
3const supabaseUrl = process.env.REACT_APP_SUPABASE_URL
4const supabaseAnonKey = process.env.REACT_APP_SUPABASE_ANON_KEY
5
6export 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.

src/Auth.js
1import { useState } from 'react'
2import { supabase } from './supabaseClient'
3
4export default function Auth() {
5  const [loading, setLoading] = useState(false)
6  const [email, setEmail] = useState('')
7
8  const handleLogin = async (e) => {
9    e.preventDefault()
10
11    try {
12      setLoading(true)
13      const { error } = await supabase.auth.signInWithOtp({ email })
14      if (error) throw error
15      alert('Check your email for the login link!')
16    } catch (error) {
17      alert(error.error_description || error.message)
18    } finally {
19      setLoading(false)
20    }
21  }
22
23  return (
24    <div className="row flex-center flex">
25      <div className="col-6 form-widget" aria-live="polite">
26        <h1 className="header">Supabase + React</h1>
27        <p className="description">Sign in via magic link with your email below</p>
28        {loading ? (
29          'Sending magic link...'
30        ) : (
31          <form onSubmit={handleLogin}>
32            <label htmlFor="email">Email</label>
33            <input
34              id="email"
35              className="inputField"
36              type="email"
37              placeholder="Your email"
38              value={email}
39              onChange={(e) => setEmail(e.target.value)}
40            />
41            <button className="button block" aria-live="polite">
42              Send magic link
43            </button>
44          </form>
45        )}
46      </div>
47    </div>
48  )
49}

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

src/Account.js
1import { useState, useEffect } from 'react'
2import { supabase } from './supabaseClient'
3
4const Account = ({ session }) => {
5  const [loading, setLoading] = useState(true)
6  const [username, setUsername] = useState(null)
7  const [website, setWebsite] = useState(null)
8  const [avatar_url, setAvatarUrl] = useState(null)
9
10  useEffect(() => {
11    getProfile()
12  }, [session])
13
14  const getProfile = async () => {
15    try {
16      setLoading(true)
17      const { user } = session
18
19      let { data, error, status } = await supabase
20        .from('profiles')
21        .select(`username, website, avatar_url`)
22        .eq('id', user.id)
23        .single()
24
25      if (error && status !== 406) {
26        throw error
27      }
28
29      if (data) {
30        setUsername(data.username)
31        setWebsite(data.website)
32        setAvatarUrl(data.avatar_url)
33      }
34    } catch (error) {
35      alert(error.message)
36    } finally {
37      setLoading(false)
38    }
39  }
40
41  const updateProfile = async (e) => {
42    e.preventDefault()
43
44    try {
45      setLoading(true)
46      const { user } = session
47
48      const updates = {
49        id: user.id,
50        username,
51        website,
52        avatar_url,
53        updated_at: new Date(),
54      }
55
56      let { error } = await supabase.from('profiles').upsert(updates)
57
58      if (error) {
59        throw error
60      }
61    } catch (error) {
62      alert(error.message)
63    } finally {
64      setLoading(false)
65    }
66  }
67
68  return (
69    <div aria-live="polite">
70      {loading ? (
71        'Saving ...'
72      ) : (
73        <form onSubmit={updateProfile} className="form-widget">
74          <div>Email: {session.user.email}</div>
75          <div>
76            <label htmlFor="username">Name</label>
77            <input
78              id="username"
79              type="text"
80              value={username || ''}
81              onChange={(e) => setUsername(e.target.value)}
82            />
83          </div>
84          <div>
85            <label htmlFor="website">Website</label>
86            <input
87              id="website"
88              type="url"
89              value={website || ''}
90              onChange={(e) => setWebsite(e.target.value)}
91            />
92          </div>
93          <div>
94            <button className="button primary block" disabled={loading}>
95              Update profile
96            </button>
97          </div>
98        </form>
99      )}
100      <button type="button" className="button block" onClick={() => supabase.auth.signOut()}>
101        Sign Out
102      </button>
103    </div>
104  )
105}
106
107export default Account

Launch!#

Now that we have all the components in place, let's update App.js:

src/App.js
1import './index.css'
2import { useState, useEffect } from 'react'
3import { supabase } from './supabaseClient'
4import Auth from './Auth'
5import Account from './Account'
6
7export default function App() {
8  const [session, setSession] = useState(null)
9
10  useEffect(() => {
11    supabase.auth.getSession().then(({ data: { session } }) => {
12      setSession(session)
13    })
14
15    supabase.auth.onAuthStateChange((_event, session) => {
16      setSession(session)
17    })
18  }, [])
19
20  return (
21    <div className="container" style={{ padding: '50px 0 100px 0' }}>
22      {!session ? <Auth /> : <Account key={session.user.id} session={session} />}
23    </div>
24  )
25}

Once that's done, run this in a terminal window:

npm start

And then open the browser to localhost:3000 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:

src/Avatar.js
1import { useEffect, useState } from 'react'
2import { supabase } from './supabaseClient'
3
4export default function Avatar({ url, size, onUpload }) {
5  const [avatarUrl, setAvatarUrl] = useState(null)
6  const [uploading, setUploading] = useState(false)
7
8  useEffect(() => {
9    if (url) downloadImage(url)
10  }, [url])
11
12  const downloadImage = async (path) => {
13    try {
14      const { data, error } = await supabase.storage.from('avatars').download(path)
15      if (error) {
16        throw error
17      }
18      const url = URL.createObjectURL(data)
19      setAvatarUrl(url)
20    } catch (error) {
21      console.log('Error downloading image: ', error.message)
22    }
23  }
24
25  const uploadAvatar = async (event) => {
26    try {
27      setUploading(true)
28
29      if (!event.target.files || event.target.files.length === 0) {
30        throw new Error('You must select an image to upload.')
31      }
32
33      const file = event.target.files[0]
34      const fileExt = file.name.split('.').pop()
35      const fileName = `${Math.random()}.${fileExt}`
36      const filePath = `${fileName}`
37
38      let { error: uploadError } = await supabase.storage.from('avatars').upload(filePath, file)
39
40      if (uploadError) {
41        throw uploadError
42      }
43
44      onUpload(filePath)
45    } catch (error) {
46      alert(error.message)
47    } finally {
48      setUploading(false)
49    }
50  }
51
52  return (
53    <div style={{ width: size }} aria-live="polite">
54      <img
55        src={avatarUrl ? avatarUrl : `https://place-hold.it/${size}x${size}`}
56        alt={avatarUrl ? 'Avatar' : 'No image'}
57        className="avatar image"
58        style={{ height: size, width: size }}
59      />
60      {uploading ? (
61        'Uploading...'
62      ) : (
63        <>
64          <label className="button primary block" htmlFor="single">
65            Upload an avatar
66          </label>
67          <div className="visually-hidden">
68            <input
69              type="file"
70              id="single"
71              accept="image/*"
72              onChange={uploadAvatar}
73              disabled={uploading}
74            />
75          </div>
76        </>
77      )}
78    </div>
79  )
80}

Add the new widget#

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

src/Account.js
1// Import the new component
2import Avatar from './Avatar'
3
4// ...
5
6return (
7  <div className="form-widget">
8    {/* Add to the body */}
9    <Avatar
10      url={avatar_url}
11      size={150}
12      onUpload={(url) => {
13        setAvatarUrl(url)
14        updateProfile({ username, website, avatar_url: url })
15      }}
16    />
17    {/* ... */}
18  </div>
19)

Next steps#

At this stage you have a fully functional application!