Quickstart: SvelteKit

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:

Supabase User Management example

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#

  1. Go to app.supabase.com.
  2. Click on "New Project".
  3. Enter your project details.
  4. 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.

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.

  1. Go to the Settings page in the Dashboard.
  2. Click API in the sidebar.
  3. Find your API 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 SvelteKit Skeleton Project to initialize an app called supabase-sveltekit (for this tutorial you do not need TypeScript, ESLint, Prettier, or Playwright):

npm init svelte@next supabase-sveltekit
cd supabase-sveltekit
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 SUPABASE_URL and the SUPABASE_KEY key that you copied earlier.

.env
PUBLIC_SUPABASE_URL="YOUR_SUPABASE_URL"
PUBLIC_SUPABASE_ANON_KEY="YOUR_SUPABASE_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/lib/supabaseClient.ts
1import { createClient } from '@supabase/auth-helpers-sveltekit'
2import { env } from '$env/dynamic/public'
3
4export const supabase = createClient(env.PUBLIC_SUPABASE_URL, env.PUBLIC_SUPABASE_ANON_KEY)

And one optional step is to update the CSS file public/global.css to make the app look nice. You can find the full contents of this file here.

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:

npm install @supabase/auth-helpers-sveltekit

Update your src/routes/+layout.svelte:

src/routes/+layout.svelte
1<script lang="ts">
2  import { supabase } from '$lib/supabaseClient'
3  import { invalidate } from '$app/navigation'
4  import { onMount } from 'svelte'
5  import './styles.css'
6
7  onMount(() => {
8    const {
9      data: { subscription },
10    } = supabase.auth.onAuthStateChange(() => {
11      invalidate('supabase:auth')
12    })
13
14    return () => {
15      subscription.unsubscribe()
16    }
17  })
18</script>
19
20<div class="container" style="padding: 50px 0 100px 0">
21  <slot />
22</div>

Create a new src/routes/+layout.ts file to handle the session on the client-side.

src/routes/+layout.ts
1import type { LayoutLoad } from './$types'
2import { getSupabase } from '@supabase/auth-helpers-sveltekit'
3
4export const load: LayoutLoad = async (event) => {
5  const { session } = await getSupabase(event)
6  return { session }
7}

Create a new src/routes/+layout.server.ts file to handle the session on the server-side.

src/routes/+layout.server.ts
1import type { LayoutServerLoad } from './$types'
2import { getServerSession } from '@supabase/auth-helpers-sveltekit'
3
4export const load: LayoutServerLoad = async (event) => {
5  return {
6    session: await getServerSession(event),
7  }
8}

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.

src/hooks.client.ts
1import '$lib/supabaseClient'
src/hooks.server.ts
1import '$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.

src/routes/Auth.svelte
1<script lang="ts">
2  import { supabase } from '$lib/supabaseClient'
3
4  let loading = false
5  let email: string
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 the 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<form class="row flex-center flex" on:submit|preventDefault="{handleLogin}">
24  <div class="col-6 form-widget">
25    <h1 class="header">Supabase + SvelteKit</h1>
26    <p class="description">Sign in via magic link with your email below</p>
27    <div>
28      <input class="inputField" type="email" placeholder="Your email" bind:value="{email}" />
29    </div>
30    <div>
31      <input type="submit" class="button block" value={loading ? 'Loading' : 'Send magic link'}
32      disabled={loading} />
33    </div>
34  </div>
35</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 to handle this functionality.

src/routes/Account.svelte
1<script lang="ts">
2  import { onMount } from 'svelte'
3  import type { AuthSession } from '@supabase/supabase-js'
4  import { supabase } from '$lib/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 (data) {
29        username = data.username
30        website = data.website
31        avatarUrl = data.avatar_url
32      }
33
34      if (error && status !== 406) throw error
35    } catch (error) {
36      if (error instanceof Error) {
37        alert(error.message)
38      }
39    } finally {
40      loading = false
41    }
42  }
43
44  async function updateProfile() {
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(),
55      }
56
57      let { error } = await supabase.from('profiles').upsert(updates)
58
59      if (error) throw error
60    } catch (error) {
61      if (error instanceof Error) {
62        alert(error.message)
63      }
64    } finally {
65      loading = false
66    }
67  }
68
69  async function signOut() {
70    try {
71      loading = true
72      let { error } = await supabase.auth.signOut()
73      if (error) throw error
74    } catch (error) {
75      if (error instanceof Error) {
76        alert(error.message)
77      }
78    } finally {
79      loading = false
80    }
81  }
82</script>
83
84<form class="form-widget" on:submit|preventDefault="{updateProfile}">
85  <div>
86    <label for="email">Email</label>
87    <input id="email" type="text" value="{session.user.email}" disabled />
88  </div>
89  <div>
90    <label for="username">Name</label>
91    <input id="username" type="text" bind:value="{username}" />
92  </div>
93  <div>
94    <label for="website">Website</label>
95    <input id="website" type="website" bind:value="{website}" />
96  </div>
97
98  <div>
99    <input type="submit" class="button block primary" value={loading ? 'Loading...' : 'Update'}
100    disabled={loading} />
101  </div>
102
103  <div>
104    <button class="button block" on:click="{signOut}" disabled="{loading}">Sign Out</button>
105  </div>
106</form>

Launch!#

Now that we have all the components in place, let's update src/routes/+page.svelte:

src/routes/+page.svelte
1<script>
2  import { page } from '$app/stores'
3  import Account from './Account.svelte'
4  import Auth from './Auth.svelte'
5</script>
6
7<svelte:head>
8  <title>Supabase + SvelteKit</title>
9  <meta name="description" content="SvelteKit using supabase-js v2" />
10</svelte:head>
11
12{#if !$page.data.session}
13<Auth />
14{:else}
15<Account session="{$page.data.session}" />
16{/if}

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.

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/routes/Avatar.svelte
1<script lang="ts">
2  import { createEventDispatcher } from 'svelte'
3  import { supabase } from '$lib/supabaseClient'
4
5  export let size = 10
6  export let url: string
7
8  let avatarUrl: string | null = 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>
64  {#if avatarUrl} <img src={avatarUrl} alt={avatarUrl ? 'Avatar' : 'No image'} class="avatar image"
65  style="height: {size}em; width: {size}em;" /> {:else}
66  <div class="avatar no-image" style="height: {size}em; width: {size}em;" />
67  {/if}
68
69  <div style="width: {size}em;">
70    <label class="button primary block" for="single">
71      {uploading ? 'Uploading ...' : 'Upload'}
72    </label>
73    <input
74      style="visibility: hidden; position:absolute;"
75      type="file"
76      id="single"
77      accept="image/*"
78      bind:files
79      on:change="{uploadAvatar}"
80      disabled="{uploading}"
81    />
82  </div>
83</div>

Add the new widget#

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

src/routes/Account.svelte
1<script>
2  // Import the new component
3  import Avatar from './Avatar.svelte'
4</script>
5
6<form use:getProfile class="form-widget" on:submit|preventDefault="{updateProfile}">
7  <!-- Add to body -->
8  <Avatar bind:url="{avatarUrl}" size="{10}" on:upload="{updateProfile}" />
9
10  <!-- Other form elements -->
11</form>

Next steps#

At this stage you have a fully functional application!