Build a User Management App with Svelte
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.
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#
- Create a new project in the Supabase Dashboard.
- 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.
- Go to the SQL Editor page in the Dashboard.
- Click User Management Starter.
- 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 Project URL and anon
key from the API settings.
- Go to the API Settings page in the Dashboard.
- Find your Project
URL
,anon
, andservice_role
keys on this page.
Building the App#
Let's start building the Svelte app from scratch.
Initialize a Svelte app#
We can use the Vite Svelte TypeScript Template to initialize an app called supabase-svelte
:
1npm create vite@latest supabase-svelte -- --template svelte-ts 2cd supabase-svelte 3npm install
Then let's install the only additional dependency: supabase-js
1npm 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.
1VITE_SUPABASE_URL=YOUR_SUPABASE_URL 2VITE_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.
import { createClient } from '@supabase/supabase-js' const supabaseUrl = import.meta.env.VITE_SUPABASE_URL const supabaseAnonKey = import.meta.env.VITE_SUPABASE_ANON_KEY export const supabase = createClient(supabaseUrl, supabaseAnonKey)
And one optional step is to update the CSS file src/app.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 Svelte component to manage logins and sign ups. We'll use Magic Links, so users can sign in with their email without using passwords.
<script lang="ts"> import { supabase } from 'src/supabaseClient' let loading = false let email = '' const handleLogin = async () => { try { loading = true const { error } = await supabase.auth.signInWithOtp({ email }) if (error) throw error alert('Check your email for login link!') } catch (error) { if (error instanceof Error) { alert(error.message) } } finally { loading = false } } </script> <div class="row flex-center flex"> <div class="col-6 form-widget" aria-live="polite"> <h1 class="header">Supabase + Svelte</h1> <p class="description">Sign in via magic link with your email below</p> <form class="form-widget" on:submit|preventDefault="{handleLogin}"> <div> <label for="email">Email</label> <input id="email" class="inputField" type="email" placeholder="Your email" bind:value="{email}" /> </div> <div> <button type="submit" class="button block" aria-live="polite" disabled="{loading}"> <span>{loading ? 'Loading' : 'Send magic link'}</span> </button> </div> </form> </div> </div>
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.svelte
.
<script lang="ts"> import { onMount } from "svelte"; import type { AuthSession } from "@supabase/supabase-js"; import { supabase } from "../supabaseClient"; export let session: AuthSession; let loading = false let username: string | null = null let website: string | null = null let avatarUrl: string | null = null onMount(() => { getProfile() }) const getProfile = async () => { try { loading = true const { user } = session const { 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 = data.username website = data.website avatarUrl = data.avatar_url } } catch (error) { if (error instanceof Error) { alert(error.message) } } finally { loading = false } } const updateProfile = async () => { try { loading = true const { user } = session const updates = { id: user.id, username, website, avatar_url: avatarUrl, updated_at: new Date().toISOString(), } let { error } = await supabase.from('profiles').upsert(updates) if (error) { throw error } } catch (error) { if (error instanceof Error) { alert(error.message) } } finally { loading = false } } </script> <form on:submit|preventDefault={updateProfile} class="form-widget"> <div>Email: {session.user.email}</div> <div> <label for="username">Name</label> <input id="username" type="text" bind:value={username} /> </div> <div> <label for="website">Website</label> <input id="website" type="text" bind:value={website} /> </div> <div> <button type="submit" class="button primary block" disabled={loading}> {loading ? 'Saving ...' : 'Update profile'} </button> </div> <button type="button" class="button block" on:click={() => supabase.auth.signOut()}> Sign Out </button> </form>
Launch!#
Now that we have all the components in place, let's update App.svelte
:
<script lang="ts"> import { onMount } from 'svelte' import { supabase } from './supabaseClient' import type { AuthSession } from '@supabase/supabase-js' import Account from './lib/Account.svelte' import Auth from './lib/Auth.svelte' let session: AuthSession onMount(() => { supabase.auth.getSession().then(({ data }) => { session = data.session }) supabase.auth.onAuthStateChange((_event, _session) => { session = _session }) }) </script> <div class="container" style="padding: 50px 0 100px 0"> {#if !session} <Auth /> {:else} <Account {session} /> {/if} </div>
Once that's done, run this in a terminal window:
1npm run dev
And then open the browser to localhost:5173 and you should see the completed app.
⚠️ WARNING: Svelte uses Vite and the default port is
5173
, Supabase usesport 3000
. To change the redirection port for supabase go to:Authentication > Settings
and change theSite Url
tolocalhost:5173
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:
<script lang="ts"> import { createEventDispatcher } from 'svelte' import { supabase } from '../supabaseClient' export let size: number export let url: string let avatarUrl: string = null let uploading = false let files: FileList const dispatch = createEventDispatcher() const downloadImage = async (path: string) => { try { const { data, error } = await supabase.storage.from('avatars').download(path) if (error) { throw error } const url = URL.createObjectURL(data) avatarUrl = url } catch (error) { if (error instanceof Error) { console.log('Error downloading image: ', error.message) } } } const uploadAvatar = async () => { try { uploading = true if (!files || files.length === 0) { throw new Error('You must select an image to upload.') } const file = files[0] const fileExt = file.name.split('.').pop() const filePath = `${Math.random()}.${fileExt}` let { error } = await supabase.storage.from('avatars').upload(filePath, file) if (error) { throw error } url = filePath dispatch('upload') } catch (error) { if (error instanceof Error) { alert(error.message) } } finally { uploading = false } } $: if (url) downloadImage(url) </script> <div style="width: {size}px" aria-live="polite"> {#if avatarUrl} <img src={avatarUrl} alt={avatarUrl ? 'Avatar' : 'No image'} class="avatar image" style="height: {size}px, width: {size}px" /> {:else} <div class="avatar no-image" style="height: {size}px, width: {size}px" /> {/if} <div style="width: {size}px"> <label class="button primary block" for="single"> {uploading ? 'Uploading ...' : 'Upload avatar'} </label> <span style="display:none"> <input type="file" id="single" accept="image/*" bind:files on:change="{uploadAvatar}" disabled="{uploading}" /> </span> </div> </div>
Add the new widget#
And then we can add the widget to the Account page:
<script lang="ts"> // Import the new component import Avatar from './Avatar.svelte' </script> <form on:submit|preventDefault="{updateProfile}" class="form-widget"> <!-- Add to body --> <Avatar bind:url="{avatarUrl}" size="{150}" on:upload="{updateProfile}" /> <!-- Other form elements --> </form>
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; $$;
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();
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();
At this stage you have a fully functional application!