Quickstart: Svelte
Intro#
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 Vite Svelte TypeScript Template to initialize an app called supabase-svelte
:
npm create vite@latest supabase-svelte -- --template svelte-ts cd supabase-svelte npm install
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
.
All we need are the API URL and the anon
key that you copied earlier.
.envVITE_SUPABASE_URL=YOUR_SUPABASE_URL 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.ts1import { createClient } from '@supabase/supabase-js' 2 3const supabaseUrl = import.meta.env.VITE_SUPABASE_URL 4const supabaseAnonKey = import.meta.env.VITE_SUPABASE_ANON_KEY 5 6export 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.
src/lib/Auth.svelte1<script lang="ts"> 2 import { supabase } from 'src/supabaseClient' 3 4 let loading = false 5 let email = '' 6 7 const handleLogin = async () => { 8 try { 9 loading = true 10 const { error } = await supabase.auth.signInWithOtp({ email }) 11 if (error) throw error 12 alert('Check your email for login link!') 13 } catch (error) { 14 if (error instanceof Error) { 15 alert(error.message) 16 } 17 } finally { 18 loading = false 19 } 20 } 21</script> 22 23<div class="row flex-center flex"> 24 <div class="col-6 form-widget" aria-live="polite"> 25 <h1 class="header">Supabase + Svelte</h1> 26 <p class="description">Sign in via magic link with your email below</p> 27 <form class="form-widget" on:submit|preventDefault="{handleLogin}"> 28 <div> 29 <label for="email">Email</label> 30 <input 31 id="email" 32 class="inputField" 33 type="email" 34 placeholder="Your email" 35 bind:value="{email}" 36 /> 37 </div> 38 <div> 39 <button type="submit" class="button block" aria-live="polite" disabled="{loading}"> 40 <span>{loading ? 'Loading' : 'Send magic link'}</span> 41 </button> 42 </div> 43 </form> 44 </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.svelte1<script lang="ts"> 2 import { onMount } from "svelte"; 3 import type { AuthSession } from "@supabase/supabase-js"; 4 import { supabase } from "../supabaseClient"; 5 6 export let session: AuthSession; 7 8 let loading = false 9 let username: string | null = null 10 let website: string | null = null 11 let avatarUrl: string | null = null 12 13 onMount(() => { 14 getProfile() 15 }) 16 17 const getProfile = async () => { 18 try { 19 loading = true 20 const { user } = session 21 22 const { data, error, status } = await supabase 23 .from('profiles') 24 .select('username, website, avatar_url') 25 .eq('id', user.id) 26 .single() 27 28 if (error && status !== 406) throw error 29 30 if (data) { 31 username = data.username 32 website = data.website 33 avatarUrl = data.avatar_url 34 } 35 } catch (error) { 36 if (error instanceof Error) { 37 alert(error.message) 38 } 39 } finally { 40 loading = false 41 } 42 } 43 44 const updateProfile = async () => { 45 try { 46 loading = true 47 const { user } = session 48 49 const updates = { 50 id: user.id, 51 username, 52 website, 53 avatar_url: avatarUrl, 54 updated_at: new Date().toISOString(), 55 } 56 57 let { error } = await supabase.from('profiles').upsert(updates) 58 59 if (error) { 60 throw error 61 } 62 } catch (error) { 63 if (error instanceof Error) { 64 alert(error.message) 65 } 66 } finally { 67 loading = false 68 } 69 } 70</script> 71 72<form on:submit|preventDefault={updateProfile} class="form-widget"> 73 <div>Email: {session.user.email}</div> 74 <div> 75 <label for="username">Name</label> 76 <input id="username" type="text" bind:value={username} /> 77 </div> 78 <div> 79 <label for="website">Website</label> 80 <input id="website" type="text" bind:value={website} /> 81 </div> 82 <div> 83 <button type="submit" class="button primary block" disabled={loading}> 84 {loading ? 'Saving ...' : 'Update profile'} 85 </button> 86 </div> 87 <button type="button" class="button block" on:click={() => supabase.auth.signOut()}> 88 Sign Out 89 </button> 90</form>
Launch!#
Now that we have all the components in place, let's update App.svelte
:
src/App.svelte1<script lang="ts"> 2 import { onMount } from 'svelte' 3 import { supabase } from './supabaseClient' 4 import type { AuthSession } from '@supabase/supabase-js' 5 import Account from './lib/Account.svelte' 6 import Auth from './lib/Auth.svelte' 7 8 let session: AuthSession 9 10 onMount(() => { 11 supabase.auth.getSession().then(({ data }) => { 12 session = data.session 13 }) 14 15 supabase.auth.onAuthStateChange((_event, _session) => { 16 session = _session 17 }) 18 }) 19</script> 20 21<div class="container" style="padding: 50px 0 100px 0"> 22 {#if !session} 23 <Auth /> 24 {:else} 25 <Account {session} /> 26 {/if} 27</div>
Once that's done, run this in a terminal window:
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 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:
src/lib/Avatar.svelte1<script lang="ts"> 2 import { createEventDispatcher } from 'svelte' 3 import { supabase } from '../supabaseClient' 4 5 export let size: number 6 export let url: string 7 8 let avatarUrl: string = null 9 let uploading = false 10 let files: FileList 11 12 const dispatch = createEventDispatcher() 13 14 const downloadImage = async (path: string) => { 15 try { 16 const { data, error } = await supabase.storage.from('avatars').download(path) 17 18 if (error) { 19 throw error 20 } 21 22 const url = URL.createObjectURL(data) 23 avatarUrl = url 24 } catch (error) { 25 if (error instanceof Error) { 26 console.log('Error downloading image: ', error.message) 27 } 28 } 29 } 30 31 const uploadAvatar = async () => { 32 try { 33 uploading = true 34 35 if (!files || files.length === 0) { 36 throw new Error('You must select an image to upload.') 37 } 38 39 const file = files[0] 40 const fileExt = file.name.split('.').pop() 41 const filePath = `${Math.random()}.${fileExt}` 42 43 let { error } = await supabase.storage.from('avatars').upload(filePath, file) 44 45 if (error) { 46 throw error 47 } 48 49 url = filePath 50 dispatch('upload') 51 } catch (error) { 52 if (error instanceof Error) { 53 alert(error.message) 54 } 55 } finally { 56 uploading = false 57 } 58 } 59 60 $: if (url) downloadImage(url) 61</script> 62 63<div style="width: {size}px" aria-live="polite"> 64 {#if avatarUrl} <img src={avatarUrl} alt={avatarUrl ? 'Avatar' : 'No image'} class="avatar image" 65 style="height: {size}px, width: {size}px" /> {:else} 66 <div class="avatar no-image" style="height: {size}px, width: {size}px" /> 67 {/if} 68 <div style="width: {size}px"> 69 <label class="button primary block" for="single"> 70 {uploading ? 'Uploading ...' : 'Upload avatar'} 71 </label> 72 <span style="display:none"> 73 <input 74 type="file" 75 id="single" 76 accept="image/*" 77 bind:files 78 on:change="{uploadAvatar}" 79 disabled="{uploading}" 80 /> 81 </span> 82 </div> 83</div>
Add the new widget#
And then we can add the widget to the Account page:
src/lib/Account.svelte1<script lang="ts"> 2 // Import the new component 3 import Avatar from './Avatar.svelte' 4</script> 5 6<form on:submit|preventDefault="{updateProfile}" class="form-widget"> 7 <!-- Add to body --> 8 <Avatar bind:url="{avatarUrl}" size="{150}" on:upload="{updateProfile}" /> 9 10 <!-- Other form elements --> 11</form>
Next steps#
At this stage you have a fully functional application!
- Got a question? Ask here.
- Sign in: app.supabase.com