Quickstart: SvelteKit
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:
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#
- Go to app.supabase.com.
- 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.
- 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 URL and anon
key from the API settings.
- Go to the Settings page in the Dashboard.
- Click API in the sidebar.
- Find your API
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 SvelteKit Skeleton Project to initialize
an app called supabase-sveltekit
(for this tutorial you do not need TypeScript, ESLint, Prettier, or Playwright):
1npm init svelte@next supabase-sveltekit 2cd supabase-sveltekit 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 SUPABASE_URL
and the SUPABASE_KEY
key that you copied earlier.
1PUBLIC_SUPABASE_URL="YOUR_SUPABASE_URL" 2PUBLIC_SUPABASE_ANON_KEY="YOUR_SUPABASE_KEY"
Now that we have the API credentials in place, create a src/lib/supabaseClient.ts
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/auth-helpers-sveltekit' import { env } from '$env/dynamic/public' export const supabase = createClient(env.PUBLIC_SUPABASE_URL, env.PUBLIC_SUPABASE_ANON_KEY)
Optionally, update src/routes/style.css
with the CSS from the example.
Supabase Auth Helpers#
SvelteKit is a highly versatile framework offering pre-rendering at build time (SSG), server-side rendering at request time (SSR), API routes, and more.
It can be challenging to authenticate your users in all these different environments, that's why we've created the Supabase Auth Helpers to make user management and data fetching within SvelteKit as easy as possible.
Install the auth helpers for SvelteKit:
1npm install @supabase/auth-helpers-sveltekit
Update your src/routes/+layout.svelte
:
<script lang="ts"> import { supabase } from '$lib/supabaseClient' import { invalidate } from '$app/navigation' import { onMount } from 'svelte' import './styles.css' onMount(() => { const { data: { subscription }, } = supabase.auth.onAuthStateChange(() => { invalidate('supabase:auth') }) return () => { subscription.unsubscribe() } }) </script> <div class="container" style="padding: 50px 0 100px 0"> <slot /> </div>
Create a new src/routes/+layout.ts
file to handle the session on the client-side.
import type { LayoutLoad } from './$types' import { getSupabase } from '@supabase/auth-helpers-sveltekit' export const load: LayoutLoad = async (event) => { const { session } = await getSupabase(event) return { session } }
Create a new src/routes/+layout.server.ts
file to handle the session on the server-side.
import type { LayoutServerLoad } from './$types'
import { getServerSession } from '@supabase/auth-helpers-sveltekit'
export const load: LayoutServerLoad = async (event) => {
return {
session: await getServerSession(event),
}
}
Be sure to create src/hooks.client.ts
and src/hooks.server.ts
in order to get the auth helper started on the client and server-side.
import '$lib/supabaseClient'
import '$lib/supabaseClient'
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.
Create a new Auth.svelte
component in the src/routes
directory to handle this functionality.
<script lang="ts"> import { supabase } from '$lib/supabaseClient' let loading = false let email: string const handleLogin = async () => { try { loading = true const { error } = await supabase.auth.signInWithOtp({ email }) if (error) throw error alert('Check your email for the login link!') } catch (error) { if (error instanceof Error) { alert(error.message) } } finally { loading = false } } </script> <form class="row flex-center flex" on:submit|preventDefault="{handleLogin}"> <div class="col-6 form-widget"> <h1 class="header">Supabase + SvelteKit</h1> <p class="description">Sign in via magic link with your email below</p> <div> <input class="inputField" type="email" placeholder="Your email" bind:value="{email}" /> </div> <div> <input type="submit" class="button block" value={loading ? 'Loading' : 'Send magic link'} disabled={loading} /> </div> </div> </form>
Account component#
After a user is signed in, they need to be able to edit their profile details and manage their account.
Create a new Account.svelte
component in the src/routes
directory to handle this functionality.
<script lang="ts"> import { onMount } from 'svelte' import type { AuthSession } from '@supabase/supabase-js' import { supabase } from '$lib/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 (data) { username = data.username website = data.website avatarUrl = data.avatar_url } if (error && status !== 406) throw error } catch (error) { if (error instanceof Error) { alert(error.message) } } finally { loading = false } } async function updateProfile() { try { loading = true const { user } = session const updates = { id: user.id, username, website, avatar_url: avatarUrl, updated_at: new Date(), } let { error } = await supabase.from('profiles').upsert(updates) if (error) throw error } catch (error) { if (error instanceof Error) { alert(error.message) } } finally { loading = false } } async function signOut() { try { loading = true let { error } = await supabase.auth.signOut() if (error) throw error } catch (error) { if (error instanceof Error) { alert(error.message) } } finally { loading = false } } </script> <form class="form-widget" on:submit|preventDefault="{updateProfile}"> <div> <label for="email">Email</label> <input id="email" type="text" value="{session.user.email}" disabled /> </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="website" bind:value="{website}" /> </div> <div> <input type="submit" class="button block primary" value={loading ? 'Loading...' : 'Update'} disabled={loading} /> </div> <div> <button class="button block" on:click="{signOut}" disabled="{loading}">Sign Out</button> </div> </form>
Launch!#
Now that we have all the components in place, let's update src/routes/+page.svelte
:
<script> import { page } from '$app/stores' import Account from './Account.svelte' import Auth from './Auth.svelte' </script> <svelte:head> <title>Supabase + SvelteKit</title> <meta name="description" content="SvelteKit using supabase-js v2" /> </svelte:head> {#if !$page.data.session} <Auth /> {:else} <Account session="{$page.data.session}" /> {/if}
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.
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 called Avatar.svelte
in the src/routes
directory:
<script lang="ts"> import { createEventDispatcher } from 'svelte' import { supabase } from '$lib/supabaseClient' export let size = 10 export let url: string let avatarUrl: string | null = 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> {#if avatarUrl} <img src={avatarUrl} alt={avatarUrl ? 'Avatar' : 'No image'} class="avatar image" style="height: {size}em; width: {size}em;" /> {:else} <div class="avatar no-image" style="height: {size}em; width: {size}em;" /> {/if} <div style="width: {size}em;"> <label class="button primary block" for="single"> {uploading ? 'Uploading ...' : 'Upload'} </label> <input style="visibility: hidden; position:absolute;" type="file" id="single" accept="image/*" bind:files on:change="{uploadAvatar}" disabled="{uploading}" /> </div> </div>
Add the new widget#
And then we can add the widget to the Account page:
<script> // Import the new component import Avatar from './Avatar.svelte' </script> <form use:getProfile class="form-widget" on:submit|preventDefault="{updateProfile}"> <!-- Add to body --> <Avatar bind:url="{avatarUrl}" size="{10}" 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 varchar) returns record language 'plpgsql' security definer as $$ declare project_url varchar := '<YOURPROJECTURL>'; service_role_key varchar := '<YOURSERVICEROLEKEY>'; -- full access needed url varchar := project_url||'/storage/v1/object/'||bucket||'/'||object; begin select into status, content result.status::int, result.content::varchar 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 varchar) 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 varchar; 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();
Next steps#
At this stage you have a fully functional application!
- Got a question? Ask here.
- Sign in: app.supabase.com