DEV Community

Tilman Vogel
Tilman Vogel

Posted on

Getting started with Supabase and Quasar v2

This tutorial is based on the common supabase tutorials and 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.

Tutorial Main Page Preview

NOTE

If you get stuck while working through this guide, refer to the full example on GitHub.

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.

Using the dashboard
  1. Go to the SQL Editor page in the Dashboard.
  2. Click User Management Starter.
  3. Click Run.

Using SQL
-- Create a table for public profiles
create table profiles (
  id uuid references auth.users not null primary key,
  updated_at timestamp with time zone,
  username text unique,
  full_name text,
  avatar_url text,
  website text,

  constraint username_length check (char_length(username) >= 3)
);
-- Set up Row Level Security (RLS)
-- See https://supabase.com/docs/guides/auth/row-level-security for more details.
alter table profiles
  enable row level security;

create policy "Public profiles are viewable by everyone." on profiles
  for select using (true);

create policy "Users can insert their own profile." on profiles
  for insert with check (auth.uid() = id);

create policy "Users can update own profile." on profiles
  for update using (auth.uid() = id);

-- This trigger automatically creates a profile entry when a new user signs up via Supabase Auth.
-- See https://supabase.com/docs/guides/auth/managing-user-data#using-triggers for more details.
create function public.handle_new_user()
returns trigger as $$
begin
  insert into public.profiles (id, full_name, avatar_url)
  values (new.id, new.raw_user_meta_data->>'full_name', new.raw_user_meta_data->>'avatar_url');
  return new;
end;
$$ language plpgsql security definer;
create trigger on_auth_user_created
  after insert on auth.users
  for each row execute procedure public.handle_new_user();

-- Set up Storage!
insert into storage.buckets (id, name)
  values ('avatars', 'avatars');

-- Set up access controls for storage.
-- See https://supabase.com/docs/guides/storage#policy-examples for more details.
create policy "Avatar images are publicly accessible." on storage.objects
  for select using (bucket_id = 'avatars');

create policy "Anyone can upload an avatar." on storage.objects
  for insert with check (bucket_id = 'avatars');

create policy "Anyone can update their own avatar." on storage.objects
  for update using (auth.uid() = owner) with check (bucket_id = 'avatars');
Enter fullscreen mode Exit fullscreen mode

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

Initialize a Quasar v2 app

We can quickly use Quasar CLI to initialize an app called supabase-quasar:

yarn global add @quasar/cli
yarn create quasar

✔ What would you like to build? › App with Quasar CLI, let's go!
✔ Project folder: … supabase-quasar
✔ Pick Quasar version: › Quasar v2 (Vue 3 | latest and greatest)
✔ Pick script type: › Typescript
✔ Pick Quasar App CLI variant: › Quasar App CLI with Vite
✔ Package name: … supabase-quasar
✔ Project product name: (must start with letter if building mobile apps) … Supabase Quasar App
✔ Project description: … A Quasar Project using Supabase
✔ Author: … Me <me@supabase.io>
✔ Pick a Vue component style: › Composition API with <script setup>
✔ Pick your CSS preprocessor: › Sass with SCSS syntax
✔ Check the features needed for your project: › ESLint
✔ Pick an ESLint preset: › Prettier

? Install project dependencies? (recommended) › - Use arrow-keys. Return to submit.
❯   Yes, use yarn
Enter fullscreen mode Exit fullscreen mode

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

cd supabase-quasar
yarn add @supabase/supabase-js
Enter fullscreen mode Exit fullscreen mode

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.

VITE_SUPABASE_URL=YOUR_SUPABASE_URL
VITE_SUPABASE_ANON_KEY=YOUR_SUPABASE_ANON_KEY
Enter fullscreen mode Exit fullscreen mode

With the API credentials in place, create an src/boot/supabase.js helper file to initialize the Supabase client. These variables are exposed on the browser, and that's completely fine since we have Row Level Security enabled on our Database.

import { boot } from 'quasar/wrappers';
import { createClient } from '@supabase/supabase-js';
import { ref } from 'vue';

// declare module '@vue/runtime-core' {
//   interface ComponentCustomProperties {
//     $supabase: SupabaseClient<Database>;
//   }
// }

const supabaseUrl = import.meta.env.VITE_SUPABASE_URL;
const supabaseAnonKey = import.meta.env.VITE_SUPABASE_ANON_KEY;

type Session = Awaited<
  ReturnType<typeof supabase.auth.getSession>
>['data']['session'];

const session = ref<Session>();
let setPasswordRequested: 'initial' | 'reset' | false = false;

// Hack to process the #access_token and #error before vue-router "cleans up",
// breaking supabase.auth token processing later on
let indexSupabaseHash = window.location.hash.indexOf('#access_token');
if (indexSupabaseHash < 0)
  indexSupabaseHash = window.location.hash.indexOf('#error');
const routerHash = window.location.hash.substring(
  0,
  indexSupabaseHash >= 0 ? indexSupabaseHash : undefined
);

const supabase = createClient(supabaseUrl, supabaseAnonKey);
// must be registered immediately before returning to the event loop because
// otherwise changes triggered by the #access_token, e.g. PASSWORD_RECOVERY,
// would be missed if the **async** supabase.auth._initialize() is processed
// before the callback is registered.
supabase.auth.onAuthStateChange(async (_event, _session) => {
  // console.log('supabase.auth.onAuthStateChange', _event, _session);
  session.value = _session;
  if (_event === 'PASSWORD_RECOVERY') setPasswordRequested = 'reset';

  const userMetaData = session.value?.user.user_metadata;
  if (!userMetaData?.passwordSetup) {
    setPasswordRequested = 'initial';
  }
});

/**
 * Finalize supabase init
 *
 * Shall be called from the router initialization before it is instantiated
 * and mangles the hash parts of the window.location. This function also removes
 * the supabase hash parts and reinstates the vue-router hash parts which are
 * otherwise cleared out by supabase.auth.initialize().
 */
async function init() {
  // this waits for the async init to finish:
  const { error } = await supabase.auth.initialize();
  if (error) window.alert(error.message);
  window.location.hash = routerHash;
}

export default boot(({ router }) => {
  // for use inside Vue files (Options API) through this.$supabase
  // app.config.globalProperties.$supabase = supabase;
  // ^ ^ ^ this will allow you to use this.$supabase (for Vue Options API form)
  //       so you won't necessarily have to import supabase in each vue file
  router.beforeEach((to) => {
    if (setPasswordRequested) {
      to.query.setPassword = setPasswordRequested;
      setPasswordRequested = false;
      return to;
    }
  });
  router.afterEach((to) => {
    if (to.query.setPassword ?? false) {
      // to be implemented if you use password login:
      // execChangePassword(
      //   to.query.setPassword === 'initial'
      //     ? 'Choose password'
      //     : 'Forgot password'
      // ).then(() => {
      //   if (to.query.setPassword === 'initial')
      //     supabase.auth.updateUser({ data: { passwordSetup: true } });
      //   router.replace({ query: { setPassword: undefined } });
      // });
    }
  });
});

export { init, supabase, session };
Enter fullscreen mode Exit fullscreen mode

Also, create an src/boot/router-auth.js helper file to limit access to pages by authentication status.

import { boot } from 'quasar/wrappers';
import { session } from './supabase';

export default boot(({ router }) => {
  router.beforeEach((to) => {
    if (to.matched.some((record) => record.meta.requiresAuth ?? false)) {
      // console.log('needs auth: ', to);
      if (!session.value) {
        // console.log('no session!');
        return { name: 'auth', query: { redirect: to.fullPath } };
      }
    }
  });
});
Enter fullscreen mode Exit fullscreen mode

Add these two files to the boot section of quasar.config.js:

    boot: [
      'supabase',
      'router-auth'
    ],
Enter fullscreen mode Exit fullscreen mode

Also, replace router/index.ts with the following in order to make sure, supabase can process the URL before the router works on it:

import { route } from 'quasar/wrappers';
import {
  createMemoryHistory,
  createRouter,
  createWebHashHistory,
  createWebHistory,
} from 'vue-router';

import routes from './routes';

import { init as supabaseInit } from 'boot/supabase';

/*
 * If not building with SSR mode, you can
 * directly export the Router instantiation;
 *
 * The function below can be async too; either use
 * async/await or return a Promise which resolves
 * with the Router instance.
 */

export default route(async function (/* { store, ssrContext } */) {
  await supabaseInit();

  const createHistory = process.env.SERVER
    ? createMemoryHistory
    : (process.env.VUE_ROUTER_MODE === 'history' ? createWebHistory : createWebHashHistory);

  const Router = createRouter({
    scrollBehavior: () => ({ left: 0, top: 0 }),
    routes,

    // Leave this as is and make changes in quasar.conf.js instead!
    // quasar.conf.js -> build -> vueRouterMode
    // quasar.conf.js -> build -> publicPath
    history: createHistory(process.env.VUE_ROUTER_BASE),
  });

  return Router;
});
Enter fullscreen mode Exit fullscreen mode

Set up a Login page

Set up an src/pages/AuthPage.vue page to manage logins and sign ups. We'll use Magic Links, so users can sign in with their email without using passwords.

<script setup>
import { ref } from 'vue';
import { supabase } from 'boot/supabase';

const loading = ref(false);
const email = ref('');

const handleLogin = async () => {
  try {
    loading.value = true;
    const { error } = await supabase.auth.signInWithOtp({
      email: email.value,
    });
    if (error) throw error;
    alert('Check your email for the login link!');
  } catch (error) {
    if (error instanceof Error) {
      alert(error.message);
    }
  } finally {
    loading.value = false;
  }
};
</script>

<template>
  <form class="q-pa-md column flex-center flex" @submit.prevent="handleLogin">
    <q-card class="col-6 form-widget">
      <q-card-section class="q-gutter-md">
        <div class="text-h1">Supabase + Quasar</div>
        <div>Sign in via magic link with your email below</div>
        <q-input
          lazy-rules
          :rules="[
            (val, rules) =>
              rules.email(val) || 'Please enter a valid email address',
          ]"
          type="email"
          label="Your email"
          v-model="email"
        />
      </q-card-section>
      <q-card-actions class="q-gutter-md">
        <q-btn
          type="submit"
          color="primary"
          :label="loading ? 'Loading' : 'Send magic link'"
          :disabled="loading"
        />
      </q-card-actions>
    </q-card>
  </form>
</template>
Enter fullscreen mode Exit fullscreen mode

Account page

After a user is signed in, we can allow them to edit their profile details and manage their account. Create a new src/pages/AccountPage.vue page to handle this.

<script setup>
import { session, supabase } from 'boot/supabase';
import { onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';

const loading = ref(true);
const username = ref('');
const website = ref('');
const avatar_url = ref('');

const router = useRouter();

onMounted(() => {
  getProfile();
});

async function getProfile() {
  try {
    loading.value = true;
    const { user } = session.value;

    let { data, error, status } = await supabase
      .from('profiles')
      .select('username, website, avatar_url')
      .eq('id', user.id)
      .single();

    if (error && status !== 406) throw error;

    if (data) {
      username.value = data.username;
      website.value = data.website;
      avatar_url.value = data.avatar_url;
    }
  } catch (error) {
    alert(error.message);
  } finally {
    loading.value = false;
  }
}

async function updateProfile() {
  try {
    loading.value = true;
    const { user } = session.value;

    const updates = {
      id: user.id,
      username: username.value,
      website: website.value,
      avatar_url: avatar_url.value,
      updated_at: new Date(),
    };

    let { error } = await supabase.from('profiles').upsert(updates);

    if (error) throw error;
  } catch (error) {
    alert(error.message);
  } finally {
    loading.value = false;
  }
}

async function signOut() {
  try {
    loading.value = true;
    let { error } = await supabase.auth.signOut();
    if (error) throw error;
  } catch (error) {
    alert(error.message);
  } finally {
    loading.value = false;
  }
  router.go(0);
}
</script>

<template>
  <form class="q-pa-md column flex-center flex" @submit.prevent="updateProfile">
    <q-card class="col-6 form-widget">
      <q-card-section>
        <div class="text-h2">Account</div>
        <q-input
          id="email"
          label="Email"
          type="text"
          :model-value="session.user.email"
          disable
        />
        <q-input id="username" label="Name" type="text" v-model="username" />
        <q-input
          id="website"
          label="Website"
          type="website"
          v-model="website"
        />
      </q-card-section>
      <q-card-actions class="q-gutter-md" align="right">
        <q-btn
          type="submit"
          color="primary"
          :label="loading ? 'Loading ...' : 'Update'"
          :disabled="loading"
        />
        <q-btn flat label="Sign Out" @click="signOut" :disabled="loading" />
      </q-card-actions>
    </q-card>
  </form>
</template>
Enter fullscreen mode Exit fullscreen mode

Router

Now, use those pages in the src/router/routes.ts route definitions:

import { RouteRecordRaw } from 'vue-router';

const routes: RouteRecordRaw[] = [
  {
    path: '/',
    component: () => import('layouts/MainLayout.vue'),
    children: [{ path: '', component: () => import('pages/AccountPage.vue') }],
    meta: {
      requiresAuth: true,
    },
  },
  {
    path: '/auth',
    name: 'auth',
    component: () => import('pages/AuthPage.vue'),
  },

  // Always leave this as last one,
  // but you can also remove it
  {
    path: '/:catchAll(.*)*',
    component: () => import('pages/ErrorNotFound.vue'),
  },
];

export default routes;
Enter fullscreen mode Exit fullscreen mode

Launch!

Now that we have all the components in place, we can straight away run the app in a terminal window:

quasar dev
Enter fullscreen mode Exit fullscreen mode

which will open the completed app in your browser.

Supabase Quasar Login Screen

Bonus: Profile photos

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

Create an upload widget

Create a new src/components/AvatarUploader.vue component that allows users to upload profile photos:

<script setup>
import { ref, toRefs, watch } from 'vue';
import { supabase } from 'boot/supabase';

const prop = defineProps(['path', 'size']);
const { path, size } = toRefs(prop);

const emit = defineEmits(['upload', 'update:path']);
const uploading = ref(false);
const src = ref('');
const files = ref();
const fileselector = ref();

const downloadImage = async () => {
  try {
    const { data, error } = await supabase.storage
      .from('avatars')
      .download(path.value);
    if (error) throw error;
    src.value = URL.createObjectURL(data);
  } catch (error) {
    console.error('Error downloading image: ', error.message);
  }
};

const uploadAvatar = async (evt) => {
  files.value = evt.target.files;
  try {
    uploading.value = true;
    if (!files.value || files.value.length === 0) {
      throw new Error('You must select an image to upload.');
    }

    const file = files.value[0];
    const fileExt = file.name.split('.').pop();
    const filePath = `${Math.random()}.${fileExt}`;

    let { error: uploadError } = await supabase.storage
      .from('avatars')
      .upload(filePath, file);

    if (uploadError) throw uploadError;
    emit('update:path', filePath);
    emit('upload');
  } catch (error) {
    alert(error.message);
  } finally {
    uploading.value = false;
  }
};

watch(path, () => {
  if (path.value) downloadImage();
});
</script>

<template>
  <div>
    <q-img
      v-if="src"
      :src="src"
      alt="Avatar"
      class="avatar image"
      :style="{ height: size + 'em', width: size + 'em' }"
    />
    <div
      v-else
      class="non-selectable row avatar no-image justify-center items-center"
      :style="{ height: size + 'em', width: size + 'em' }"
      @click="fileselector.click()"
    >
      Photo
    </div>

    <div :style="{ width: size + 'em' }">
      <q-btn
        style="width: 100%"
        :label="uploading ? 'Uploading ...' : 'Pick Photo'"
        color="primary"
        :disable="uploading"
        @click="fileselector.click()"
      />
      <input
        style="visibility: hidden; position: absolute; width: 0px"
        type="file"
        id="fileselector"
        ref="fileselector"
        accept="image/*"
        @change="uploadAvatar"
        :disabled="uploading"
      />
    </div>
  </div>
</template>

<style>
.avatar {
  border-radius: var(--custom-border-radius);
  overflow: hidden;
  max-width: 100%;
}
.avatar.image {
  object-fit: cover;
}
.avatar.no-image {
  color: #eee;
  background-color: #333;
  border: 1px solid rgb(200, 200, 200);
  border-radius: var(--custom-border-radius);
}
</style>
Enter fullscreen mode Exit fullscreen mode

Add the new widget

And then, we can add the widget to the Account page in src/pages/AccountPage.vue:

<script>
// Import the new component
import AvatarUploader from 'components/AvatarUploader.vue';
</script>

<template>
  <form class="form-widget" @submit.prevent="updateProfile">
    <!-- Add to body -->
    <avatar-uploader v-model:path="avatar_url" @upload="updateProfile" size="10" />

    <!-- Other form elements -->
  </form>
</template>
Enter fullscreen mode Exit fullscreen mode

Storage management

If you upload additional profile photos, they'll accumulate in the avatars bucket because of their random names with only the latest being referenced from public.profiles and the older versions getting orphaned.

To automatically remove obsolete storage objects, extend the database triggers. Note that it is not sufficient to delete the objects from the storage.objects table because that would orphan and leak the actual storage objects in the S3 backend. Instead, invoke the storage API within Postgres via the HTTP extension.

Enable the HTTP extension for the extensions schema in the Dashboard. Then, define the following SQL functions in the SQL Editor to delete storage objects via the API:

create or replace function delete_storage_object(bucket text, object text, out status int, out content text)
returns record
language 'plpgsql'
security definer
as $$
declare
  project_url text := '<YOURPROJECTURL>';
  service_role_key text := '<YOURSERVICEROLEKEY>'; --  full access needed
  url text := project_url||'/storage/v1/object/'||bucket||'/'||object;
begin
  select
      into status, content
           result.status::int, result.content::text
      FROM extensions.http((
    'DELETE',
    url,
    ARRAY[extensions.http_header('authorization','Bearer '||service_role_key)],
    NULL,
    NULL)::extensions.http_request) as result;
end;
$$;

create or replace function delete_avatar(avatar_url text, out status int, out content text)
returns record
language 'plpgsql'
security definer
as $$
begin
  select
      into status, content
           result.status, result.content
      from public.delete_storage_object('avatars', avatar_url) as result;
end;
$$;

Enter fullscreen mode Exit fullscreen mode

Next, add a trigger that removes any obsolete avatar whenever the profile is updated or deleted:

create or replace function delete_old_avatar()
returns trigger
language 'plpgsql'
security definer
as $$
declare
  status int;
  content text;
begin
  if coalesce(old.avatar_url, '') <> ''
      and (tg_op = 'DELETE' or (old.avatar_url <> new.avatar_url)) then
    select
      into status, content
      result.status, result.content
      from public.delete_avatar(old.avatar_url) as result;
    if status <> 200 then
      raise warning 'Could not delete avatar: % %', status, content;
    end if;
  end if;
  if tg_op = 'DELETE' then
    return old;
  end if;
  return new;
end;
$$;

create trigger before_profile_changes
  before update of avatar_url or delete on public.profiles
  for each row execute function public.delete_old_avatar();

Enter fullscreen mode Exit fullscreen mode

Finally, delete the public.profile row before a user is deleted. If this step is omitted, you won't be able to delete users without first manually deleting their avatar image.

create or replace function delete_old_profile()
returns trigger
language 'plpgsql'
security definer
as $$
begin
  delete from public.profiles where id = old.id;
  return old;
end;
$$;

create trigger before_delete_user
  before delete on auth.users
  for each row execute function public.delete_old_profile();

Enter fullscreen mode Exit fullscreen mode

At this stage you have a fully functional application!

Top comments (0)