Quickstart: Vue 3

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

Initialize a Vue 3 app#

We can quickly use Vite with Vue 3 Template to initialize an app called supabase-vue-3:

# npm 6.x
npm create vite@latest supabase-vue-3 --template vue

# npm 7+, extra double-dash is needed:
npm create vite@latest supabase-vue-3 -- --template vue

cd supabase-vue-3

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
VITE_SUPABASE_URL=YOUR_SUPABASE_URL
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.

src/supabase.js
1import { createClient } from '@supabase/supabase-js'
2
3const supabaseUrl = import.meta.env.VITE_SUPABASE_URL
4const supabaseAnonKey = import.meta.env.VITE_SUPABASE_ANON_KEY
5
6export const supabase = createClient(supabaseUrl, supabaseAnonKey)

Optionally, update src/style.css to style the app.

Set up a Login component#

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

/src/components/Auth.vue
1<script setup>
2  import { ref } from 'vue'
3  import { supabase } from '../supabase'
4
5  const loading = ref(false)
6  const email = ref('')
7
8  const handleLogin = async () => {
9    try {
10      loading.value = true
11      const { error } = await supabase.auth.signInWithOtp({
12        email: email.value,
13      })
14      if (error) throw error
15      alert('Check your email for the login link!')
16    } catch (error) {
17      if (error instanceof Error) {
18        alert(error.message)
19      }
20    } finally {
21      loading.value = false
22    }
23  }
24</script>
25
26<template>
27  <form class="row flex-center flex" @submit.prevent="handleLogin">
28    <div class="col-6 form-widget">
29      <h1 class="header">Supabase + Vue 3</h1>
30      <p class="description">Sign in via magic link with your email below</p>
31      <div>
32        <input class="inputField" type="email" placeholder="Your email" v-model="email" />
33      </div>
34      <div>
35        <input
36          type="submit"
37          class="button block"
38          :value="loading ? 'Loading' : 'Send magic link'"
39          :disabled="loading"
40        />
41      </div>
42    </div>
43  </form>
44</template>

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

src/components/Account.vue
1<script setup>
2  import { supabase } from '../supabase'
3  import { onMounted, ref, toRefs } from 'vue'
4
5  const props = defineProps(['session'])
6  const { session } = toRefs(props)
7
8  const loading = ref(true)
9  const username = ref('')
10  const website = ref('')
11  const avatar_url = ref('')
12
13  onMounted(() => {
14    getProfile()
15  })
16
17  async function getProfile() {
18    try {
19      loading.value = true
20      const { user } = session.value
21
22      let { data, error, status } = await supabase
23        .from('profiles')
24        .select(`username, website, avatar_url`)
25        .eq('id', user.id)
26        .single()
27
28      if (error && status !== 406) throw error
29
30      if (data) {
31        username.value = data.username
32        website.value = data.website
33        avatar_url.value = data.avatar_url
34      }
35    } catch (error) {
36      alert(error.message)
37    } finally {
38      loading.value = false
39    }
40  }
41
42  async function updateProfile() {
43    try {
44      loading.value = true
45      const { user } = session.value
46
47      const updates = {
48        id: user.id,
49        username: username.value,
50        website: website.value,
51        avatar_url: avatar_url.value,
52        updated_at: new Date(),
53      }
54
55      let { error } = await supabase.from('profiles').upsert(updates)
56
57      if (error) throw error
58    } catch (error) {
59      alert(error.message)
60    } finally {
61      loading.value = false
62    }
63  }
64
65  async function signOut() {
66    try {
67      loading.value = true
68      let { error } = await supabase.auth.signOut()
69      if (error) throw error
70    } catch (error) {
71      alert(error.message)
72    } finally {
73      loading.value = false
74    }
75  }
76</script>
77
78<template>
79  <form class="form-widget" @submit.prevent="updateProfile">
80    <div>
81      <label for="email">Email</label>
82      <input id="email" type="text" :value="session.user.email" disabled />
83    </div>
84    <div>
85      <label for="username">Name</label>
86      <input id="username" type="text" v-model="username" />
87    </div>
88    <div>
89      <label for="website">Website</label>
90      <input id="website" type="website" v-model="website" />
91    </div>
92
93    <div>
94      <input
95        type="submit"
96        class="button primary block"
97        :value="loading ? 'Loading ...' : 'Update'"
98        :disabled="loading"
99      />
100    </div>
101
102    <div>
103      <button class="button block" @click="signOut" :disabled="loading">Sign Out</button>
104    </div>
105  </form>
106</template>

Launch!#

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

src/App.vue
1<script setup>
2  import { onMounted, ref } from 'vue'
3  import Account from './components/Account.vue'
4  import Auth from './components/Auth.vue'
5  import { supabase } from './supabase'
6
7  const session = ref()
8
9  onMounted(() => {
10    supabase.auth.getSession().then(({ data }) => {
11      session.value = data.session
12    })
13
14    supabase.auth.onAuthStateChange((_, _session) => {
15      session.value = _session
16    })
17  })
18</script>
19
20<template>
21  <div class="container" style="padding: 50px 0 100px 0">
22    <Account v-if="session" :session="session" />
23    <Auth v-else />
24  </div>
25</template>

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

npm run dev

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

Supabase Vue 3

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/components/Avatar.vue
1<script setup>
2  import { ref, toRefs, watch } from 'vue'
3  import { supabase } from '../supabase'
4
5  const prop = defineProps(['path', 'size'])
6  const { path, size } = toRefs(prop)
7
8  const emit = defineEmits(['upload', 'update:path'])
9  const uploading = ref(false)
10  const src = ref('')
11  const files = ref()
12
13  const downloadImage = async () => {
14    try {
15      const { data, error } = await supabase.storage.from('avatars').download(path.value)
16      if (error) throw error
17      src.value = URL.createObjectURL(data)
18    } catch (error) {
19      console.error('Error downloading image: ', error.message)
20    }
21  }
22
23  const uploadAvatar = async (evt) => {
24    files.value = evt.target.files
25    try {
26      uploading.value = true
27      if (!files.value || files.value.length === 0) {
28        throw new Error('You must select an image to upload.')
29      }
30
31      const file = files.value[0]
32      const fileExt = file.name.split('.').pop()
33      const filePath = `${Math.random()}.${fileExt}`
34
35      let { error: uploadError } = await supabase.storage.from('avatars').upload(filePath, file)
36
37      if (uploadError) throw uploadError
38      emit('update:path', filePath)
39      emit('upload')
40    } catch (error) {
41      alert(error.message)
42    } finally {
43      uploading.value = false
44    }
45  }
46
47  watch(path, () => {
48    if (path.value) downloadImage()
49  })
50</script>
51
52<template>
53  <div>
54    <img
55      v-if="src"
56      :src="src"
57      alt="Avatar"
58      class="avatar image"
59      :style="{ height: size + 'em', width: size + 'em' }"
60    />
61    <div v-else class="avatar no-image" :style="{ height: size + 'em', width: size + 'em' }" />
62
63    <div :style="{ width: size + 'em' }">
64      <label class="button primary block" for="single">
65        {{ uploading ? "Uploading ..." : "Upload" }}
66      </label>
67      <input
68        style="visibility: hidden; position: absolute"
69        type="file"
70        id="single"
71        accept="image/*"
72        @change="uploadAvatar"
73        :disabled="uploading"
74      />
75    </div>
76  </div>
77</template>

Add the new widget#

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

src/components/Account.vue
1<script>
2  // Import the new component
3  import Avatar from './Avatar.vue'
4</script>
5
6<template>
7  <form class="form-widget" @submit.prevent="updateProfile">
8    <!-- Add to body -->
9    <Avatar v-model:path="avatar_url" @upload="updateProfile" size="10" />
10
11    <!-- Other form elements -->
12  </form>
13</template>

Next steps#

At this stage you have a fully functional application!