Prepare for the PgBouncer and IPv4 deprecations on 26th January 2024

Home

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.

Supabase User Management example

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.

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

_10
supabase link --project-ref <project-id>
_10
# You can get <project-id> from your project's dashboard URL: https://supabase.com/dashboard/project/<project-id>
_10
supabase db pull

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

Initialize a Svelte app

We can use the Vite Svelte TypeScript Template to initialize an app called supabase-svelte:


_10
npm create vite@latest supabase-svelte -- --template svelte-ts
_10
cd supabase-svelte
_10
npm install

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


_10
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

_10
VITE_SUPABASE_URL=YOUR_SUPABASE_URL
_10
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/supabaseClient.ts

_10
import { createClient } from '@supabase/supabase-js'
_10
_10
const supabaseUrl = import.meta.env.VITE_SUPABASE_URL
_10
const supabaseAnonKey = import.meta.env.VITE_SUPABASE_ANON_KEY
_10
_10
export const supabase = createClient(supabaseUrl, supabaseAnonKey)

App styling (optional)

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

src/lib/Auth.svelte

_45
<script lang="ts">
_45
import { supabase } from '../supabaseClient'
_45
_45
let loading = false
_45
let email = ''
_45
_45
const handleLogin = async () => {
_45
try {
_45
loading = true
_45
const { error } = await supabase.auth.signInWithOtp({ email })
_45
if (error) throw error
_45
alert('Check your email for login link!')
_45
} catch (error) {
_45
if (error instanceof Error) {
_45
alert(error.message)
_45
}
_45
} finally {
_45
loading = false
_45
}
_45
}
_45
</script>
_45
_45
<div class="row flex-center flex">
_45
<div class="col-6 form-widget" aria-live="polite">
_45
<h1 class="header">Supabase + Svelte</h1>
_45
<p class="description">Sign in via magic link with your email below</p>
_45
<form class="form-widget" on:submit|preventDefault="{handleLogin}">
_45
<div>
_45
<label for="email">Email</label>
_45
<input
_45
id="email"
_45
class="inputField"
_45
type="email"
_45
placeholder="Your email"
_45
bind:value="{email}"
_45
/>
_45
</div>
_45
<div>
_45
<button type="submit" class="button block" aria-live="polite" disabled="{loading}">
_45
<span>{loading ? 'Loading' : 'Send magic link'}</span>
_45
</button>
_45
</div>
_45
</form>
_45
</div>
_45
</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.

src/lib/Account.svelte

_90
<script lang="ts">
_90
import { onMount } from 'svelte'
_90
import type { AuthSession } from '@supabase/supabase-js'
_90
import { supabase } from '../supabaseClient'
_90
_90
export let session: AuthSession
_90
_90
let loading = false
_90
let username: string | null = null
_90
let website: string | null = null
_90
let avatarUrl: string | null = null
_90
_90
onMount(() => {
_90
getProfile()
_90
})
_90
_90
const getProfile = async () => {
_90
try {
_90
loading = true
_90
const { user } = session
_90
_90
const { data, error, status } = await supabase
_90
.from('profiles')
_90
.select('username, website, avatar_url')
_90
.eq('id', user.id)
_90
.single()
_90
_90
if (error && status !== 406) throw error
_90
_90
if (data) {
_90
username = data.username
_90
website = data.website
_90
avatarUrl = data.avatar_url
_90
}
_90
} catch (error) {
_90
if (error instanceof Error) {
_90
alert(error.message)
_90
}
_90
} finally {
_90
loading = false
_90
}
_90
}
_90
_90
const updateProfile = async () => {
_90
try {
_90
loading = true
_90
const { user } = session
_90
_90
const updates = {
_90
id: user.id,
_90
username,
_90
website,
_90
avatar_url: avatarUrl,
_90
updated_at: new Date().toISOString(),
_90
}
_90
_90
const { error } = await supabase.from('profiles').upsert(updates)
_90
_90
if (error) {
_90
throw error
_90
}
_90
} catch (error) {
_90
if (error instanceof Error) {
_90
alert(error.message)
_90
}
_90
} finally {
_90
loading = false
_90
}
_90
}
_90
</script>
_90
_90
<form on:submit|preventDefault="{updateProfile}" class="form-widget">
_90
<div>Email: {session.user.email}</div>
_90
<div>
_90
<label for="username">Name</label>
_90
<input id="username" type="text" bind:value="{username}" />
_90
</div>
_90
<div>
_90
<label for="website">Website</label>
_90
<input id="website" type="text" bind:value="{website}" />
_90
</div>
_90
<div>
_90
<button type="submit" class="button primary block" disabled="{loading}">
_90
{loading ? 'Saving ...' : 'Update profile'}
_90
</button>
_90
</div>
_90
<button type="button" class="button block" on:click="{()" ="">
_90
supabase.auth.signOut()}> Sign Out
_90
</button>
_90
</form>

Launch!

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

src/App.svelte

_27
<script lang="ts">
_27
import { onMount } from 'svelte'
_27
import { supabase } from './supabaseClient'
_27
import type { AuthSession } from '@supabase/supabase-js'
_27
import Account from './lib/Account.svelte'
_27
import Auth from './lib/Auth.svelte'
_27
_27
let session: AuthSession
_27
_27
onMount(() => {
_27
supabase.auth.getSession().then(({ data }) => {
_27
session = data.session
_27
})
_27
_27
supabase.auth.onAuthStateChange((_event, _session) => {
_27
session = _session
_27
})
_27
})
_27
</script>
_27
_27
<div class="container" style="padding: 50px 0 100px 0">
_27
{#if !session}
_27
<Auth />
_27
{:else}
_27
<Account {session} />
_27
{/if}
_27
</div>

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


_10
npm 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 uses port 3000. To change the redirection port for supabase go to: Authentication > Settings and change the Site Url to http://localhost:5173/

Supabase Svelte

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/lib/Avatar.svelte

_83
<script lang="ts">
_83
import { createEventDispatcher } from 'svelte'
_83
import { supabase } from '../supabaseClient'
_83
_83
export let size: number
_83
export let url: string
_83
_83
let avatarUrl: string = null
_83
let uploading = false
_83
let files: FileList
_83
_83
const dispatch = createEventDispatcher()
_83
_83
const downloadImage = async (path: string) => {
_83
try {
_83
const { data, error } = await supabase.storage.from('avatars').download(path)
_83
_83
if (error) {
_83
throw error
_83
}
_83
_83
const url = URL.createObjectURL(data)
_83
avatarUrl = url
_83
} catch (error) {
_83
if (error instanceof Error) {
_83
console.log('Error downloading image: ', error.message)
_83
}
_83
}
_83
}
_83
_83
const uploadAvatar = async () => {
_83
try {
_83
uploading = true
_83
_83
if (!files || files.length === 0) {
_83
throw new Error('You must select an image to upload.')
_83
}
_83
_83
const file = files[0]
_83
const fileExt = file.name.split('.').pop()
_83
const filePath = `${Math.random()}.${fileExt}`
_83
_83
const { error } = await supabase.storage.from('avatars').upload(filePath, file)
_83
_83
if (error) {
_83
throw error
_83
}
_83
_83
url = filePath
_83
dispatch('upload')
_83
} catch (error) {
_83
if (error instanceof Error) {
_83
alert(error.message)
_83
}
_83
} finally {
_83
uploading = false
_83
}
_83
}
_83
_83
$: if (url) downloadImage(url)
_83
</script>
_83
_83
<div style="width: {size}px" aria-live="polite">
_83
{#if avatarUrl} <img src={avatarUrl} alt={avatarUrl ? 'Avatar' : 'No image'} class="avatar image"
_83
style="height: {size}px, width: {size}px" /> {:else}
_83
<div class="avatar no-image" style="height: {size}px, width: {size}px" />
_83
{/if}
_83
<div style="width: {size}px">
_83
<label class="button primary block" for="single">
_83
{uploading ? 'Uploading ...' : 'Upload avatar'}
_83
</label>
_83
<span style="display:none">
_83
<input
_83
type="file"
_83
id="single"
_83
accept="image/*"
_83
bind:files
_83
on:change="{uploadAvatar}"
_83
disabled="{uploading}"
_83
/>
_83
</span>
_83
</div>
_83
</div>

Add the new widget

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

src/lib/Account.svelte

_11
<script lang="ts">
_11
// Import the new component
_11
import Avatar from './Avatar.svelte'
_11
</script>
_11
_11
<form on:submit|preventDefault="{updateProfile}" class="form-widget">
_11
<!-- Add to body -->
_11
<Avatar bind:url="{avatarUrl}" size="{150}" on:upload="{updateProfile}" />
_11
_11
<!-- Other form elements -->
_11
</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:


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

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


_32
create or replace function delete_old_avatar()
_32
returns trigger
_32
language 'plpgsql'
_32
security definer
_32
as $$
_32
declare
_32
status int;
_32
content text;
_32
avatar_name text;
_32
begin
_32
if coalesce(old.avatar_url, '') <> ''
_32
and (tg_op = 'DELETE' or (old.avatar_url <> coalesce(new.avatar_url, ''))) then
_32
-- extract avatar name
_32
avatar_name := old.avatar_url;
_32
select
_32
into status, content
_32
result.status, result.content
_32
from public.delete_avatar(avatar_name) as result;
_32
if status <> 200 then
_32
raise warning 'Could not delete avatar: % %', status, content;
_32
end if;
_32
end if;
_32
if tg_op = 'DELETE' then
_32
return old;
_32
end if;
_32
return new;
_32
end;
_32
$$;
_32
_32
create trigger before_profile_changes
_32
before update of avatar_url or delete on public.profiles
_32
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.


_14
create or replace function delete_old_profile()
_14
returns trigger
_14
language 'plpgsql'
_14
security definer
_14
as $$
_14
begin
_14
delete from public.profiles where id = old.id;
_14
return old;
_14
end;
_14
$$;
_14
_14
create trigger before_delete_user
_14
before delete on auth.users
_14
for each row execute function public.delete_old_profile();

At this stage you have a fully functional application!