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:
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
Go to app.supabase.io.
Click on "New Project".
Enter your project details.
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.
-- Create a table for public "profiles"createtableprofiles(iduuidreferencesauth.usersnotnull,updated_attimestampwithtimezone,usernametextunique,avatar_urltext,websitetext,primarykey(id),unique(username),constraintusername_lengthcheck(char_length(username)>=3));altertableprofilesenablerowlevelsecurity;createpolicy"Public profiles are viewable by everyone."onprofilesforselectusing(true);createpolicy"Users can insert their own profile."onprofilesforinsertwithcheck(auth.uid()=id);createpolicy"Users can update own profile."onprofilesforupdateusing(auth.uid()=id);-- Set up Realtime!begin;droppublicationifexistssupabase_realtime;createpublicationsupabase_realtime;commit;alterpublicationsupabase_realtimeaddtableprofiles;-- Set up Storage!insertintostorage.buckets(id,name)values('avatars','avatars');createpolicy"Avatar images are publicly accessible."onstorage.objectsforselectusing(bucket_id='avatars');createpolicy"Anyone can upload an avatar."onstorage.objectsforinsertwithcheck(bucket_id='avatars');
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.
Go to the "Settings" section.
Click "API" in the sidebar.
Find your API URL in this page.
Find your "anon" and "service_role" keys on this page.
Building the App
Let's start building the Vue.js app from scratch.
Initialize a Vue App
We can use vue/cli to initialize an app called vue-user-management:
vue create vue-user-management
cd vue-user-management
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.local. All we need are the API URL and the anon key that you copied earlier.
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.
/**
* lib/supabaseClient.js
* Helper to initialize the Supabase client.
*/import{createClient}from'@supabase/supabase-js'constsupabaseUrl=process.env.VUE_APP_SUPABASE_URLconstsupabaseAnonKey=process.env.VUE_APP_SUPABASE_ANON_KEYexportconstsupabase=createClient(supabaseUrl,supabaseAnonKey)
Set Up An Auth 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. New component called Auth.vue
<template><divclass="row flex flex-center"><divclass="col-6 form-widget"><h1class="header">Supabase + Vue.js</h1><pclass="description">Sign in via magic link with your email below</p><div><inputclass="inputField"type="email"placeholder="Your email"v-model="email"/></div><div><button@click="
e => {
e.preventDefault();
handleLogin(email);
}
"
class="button block"
:disabled="loading"
>
<span>{{loading?"Loading...":"Send Magic Link"}}</span></button></div></div></div></template><scriptlang="ts">import{defineComponent,ref}from"vue";import{supabase}from"./supabaseClient";exportdefaultdefineComponent({name:"Auth",setup(){constloading=ref(false);constemail=ref("");consthandleLogin=asyncemail=>{try{loading.value=true;const{error}=awaitsupabase.auth.signIn({email});if (error)throwerror;alert("Check your email for the login link!");}catch (error){alert(error.error_description||error.message);}finally{loading.value=false;}};return{email,loading,handleLogin};}});</script><stylescoped></style>
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.
<template><divclass="form-widget"><h1class="header">Supabase + Vue.js: Account</h1><avatar:url="avatar_url"@onUpload="handleImageUpload"/><div><labelhtmlFor="email">Email</label><inputid="email"type="text":value="session.user.email"disabled/></div><div><labelhtmlFor="username">Name</label><inputid="username"type="text"v-model="username"/></div><div><labelhtmlFor="website">Website</label><inputid="website"type="website"v-model="website"/></div><div><buttonclass="button block primary"@click="updateProfile({ username, website, avatar_url })"
:disabled="loading"
>
<span>{{loading?"Loading...":"Update"}}</span></button></div><div><buttonclass="button block"@click="supabase.auth.signOut()">
Sign Out
</button></div></div></template><scriptlang="ts">import{defineComponent,ref}from"vue";importAvatarfrom"./Avatar";import{supabase}from"./supabaseClient";exportdefaultdefineComponent({name:"Account",props:["session"],components:{Avatar},setup(props){constloading=ref(false);constusername=ref("");constwebsite=ref("");constavatar_url=ref("");/**
*
*/consthandleImageUpload=asyncpath=>{avatar_url.value=path;awaitupdateProfile({username,website,avatar_url:path});};constupdateProfile=async ({username,website,avatar_url})=>{try{debugger;loading.value=true;constuser=supabase.auth.user();constupdates={id:user.id,username:username.value,website:website.value,avatar_url:(avatar_url.value||avatar_url),updated_at:newDate()};let{error}=awaitsupabase.from("profiles").upsert(updates,{returning:"minimal"// Don't return the value after inserting});if (error){throwerror;}}catch (error){alert(error.message);}finally{loading.value=false;}};constgetProfile=asyncsession=>{try{loading.value=true;constuser=session.user;let{data,error,status}=awaitsupabase.from("profiles").select(`username, website, avatar_url`).eq("id",user.id).single();if (error&&status!==406){throwerror;}if (data){username.value=data.username;website.value=data.website;avatar_url.value=data.avatar_url;}debugger;}catch (error){alert(error.message);}finally{loading.value=false;}};getProfile(props.session);return{loading,username,website,avatar_url,updateProfile,supabase,handleImageUpload};}});</script><stylescoped></style>
Bonus: Profile Photos
Every Supabase project is configured with Storage for managing large files like photos and videos.
Create an Avatar Component
Let's create an avatar for the user so that they can upload a profile photo and view an image associated with the user account. We can start by creating a new component: Avatar.vue
<template><img:src="avatarUrl"alt="Avatar"class="avatar image"style="height: 150px, width: 150px"/><divstyle="width: 150px"><inputstyle="visibility: hidden; position: absolute"type="file"id="single"accept="image/*"@change="uploadAvatar":disabled="uploading"/><labelclass="button primary block"htmlFor="single"><span>{{uploading?"UpLoading...":"Upload"}}</span></label></div></template><script>import{ref,watch}from"@vue/runtime-core";import{supabase}from"./supabaseClient";importmissingImagefrom"@/assets/no_image_available.jpeg";exportdefault{name:"Avatar",props:{url:String},emits:["onUpload"],setup(props,ctx){constavatarUrl=ref(null);constuploading=ref(false);watch(()=>props?.url,(cur)=>{downloadImage(cur);});/**
*
*/constdownloadImage=asyncpath=>{console.log("download path",path);if (!path){avatarUrl.value=missingImage;return;}const{data,error}=awaitsupabase.storage.from("avatars").download(path);if (error)throwerror;avatarUrl.value=URL.createObjectURL(data);};asyncfunctionuploadAvatar(event){debugger;try{uploading.value=true;if (!event.target.files||event.target.files.length===0){thrownewError("You must select an image to upload.");}constfile=event.target.files[0];constfileExt=file.name.split(".").pop();constfileName=`${Math.random()}.${fileExt}`;constfilePath=`${fileName}`;let{error:uploadError}=awaitsupabase.storage.from("avatars").upload(filePath,file);if (uploadError){throwuploadError;}ctx.emit("onUpload",filePath);}catch (error){alert(error.message);}finally{uploading.value=false;}}return{avatarUrl,uploading,uploadAvatar};}};</script><!-- Add "scoped" attribute to limit CSS to this component only --><stylescoped></style>
App Component
here in the app component, we are tracking the session information to determine if we should render the Auth Component or the Account component.
When the App Component is mounted we check for a session and we also set up a listener to track for authentication state changes in the application to once again render the appropriate component.