Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

Update to SvelteKit quickstart with auth helpers

Andrew Smithb9ddf6b273cd
diff --git a/apps/reference/docs/guides/with-sveltekit.mdx b/apps/reference/docs/guides/with-sveltekit.mdx
index 8cf78ec9ff4..f3c0e7b63b3 100644
--- a/apps/reference/docs/guides/with-sveltekit.mdx
+++ b/apps/reference/docs/guides/with-sveltekit.mdx
@@ -52,7 +52,7 @@ 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](/docs/guides/auth#row-level-security) enabled on our Database.
-```js title="lib/supabaseClient.ts"
+```js title="src/lib/supabaseClient.ts"
import { createClient } from '@supabase/auth-helpers-sveltekit'
import { env } from '$env/dynamic/public'
@@ -62,167 +62,241 @@ export const supabaseClient = createClient(env.PUBLIC_SUPABASE_URL, env.PUBLIC_S
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](https://raw.githubusercontent.com/supabase/supabase/master/examples/user-management/svelte-user-management/src/app.css).
-### Set up a Login component
+### Supabase Auth Helpers
-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.
+SvelteKit is a highly versatile framework offering pre-rendering at build time (SSG), server-side rendering at request time (SSR), API routes, and more.
-```html title="lib/Auth.svelte"
-<script>
- import { supabase } from '$lib/supabaseClient'
-
- let loading = false
- let email
-
- const handleLogin = async () => {
- try {
- loading = true
- const { error } = await supabase.auth.signIn({ email })
- if (error) throw error
- alert('Check your email for the login link!')
- } catch (error) {
- alert(error.error_description || error.message)
- } finally {
- loading = false
- }
- }
+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
+
+```bash
+npm install @supabase/auth-helpers-sveltekit
+```
+
+Update your `src/routes/+layout.svelte`:
+
+```html title="src/routes/+layout.svelte"
+<script lang="ts">
+ import { supabaseClient } from '$lib/supabaseClient'
+ import { invalidate } from '$app/navigation'
+ import { onMount } from 'svelte'
+ import './styles.css'
+
+ onMount(() => {
+ const {
+ data: { subscription }
+ } = supabaseClient.auth.onAuthStateChange(() => {
+ invalidate('supabase:auth')
+ })
+
+ return () => {
+ subscription.unsubscribe()
+ }
+ })
</script>
-<form class="row flex-center flex" on:submit|preventDefault="{handleLogin}">
- <div class="col-6 form-widget">
- <h1 class="header">Supabase + Svelte</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>
+<div class="container" style="padding: 50px 0 100px 0">
+ <slot />
+</div>
```
-### User store
+Create a new file called `src/routes/+layout.ts` which will take care of handling the session on the client-side.
-To access the user information in other places, we use a writable store. Create a new file called `sessionStore.js`
+```ts title="src/routes/+layout.ts"
+import type { LayoutLoad } from './$types';
+import { getSupabase } from '@supabase/auth-helpers-sveltekit';
-```javascript title="lib/sessionStore.js"
-import { writable } from 'svelte/store'
+export const load: LayoutLoad = async (event) => {
+ const { session } = await getSupabase(event);
+ return { session };
+};
+```
+
+Create another new file called `src/routes/+layout.server.ts` which will take care of handling the session on the server-side.
+
+```ts title="src/routes/+layout.server.ts"
+import type { LayoutServerLoad } from './$types';
+import { getServerSession } from '@supabase/auth-helpers-sveltekit';
-export const user = writable(false)
+export const load: LayoutServerLoad = async (event) => {
+ return {
+ session: await getServerSession(event)
+ };
+};
```
-### Account page
+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.
-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 `Profile.svelte`.
+```ts title="src/hooks.client.ts"
+import '$lib/supabaseClient'
+```
-```html title="lib/Profile.svelte"
-<script>
- import { supabase } from '$lib/supabaseClient'
- import { user } from '$lib/sessionStore'
-
- let loading = true
- let username = null
- let website = null
- let avatar_url = null
-
- function getProfile(node) {
- try {
- loading = true
- const user = supabase.auth.user()
-
- supabase
- .from('profiles')
- .select(`username, website, avatar_url`)
- .eq('id', user?.id)
- .single()
- .then(({ data, error, status }) => {
- if (data) {
- username = data.username
- website = data.website
- avatar_url = data.avatar_url
- }
- if (error && status !== 406) throw error
- })
- } catch (error) {
- alert(error.message)
- } finally {
- loading = false
- }
- }
-
- async function updateProfile() {
- try {
- loading = true
- const user = supabase.auth.user()
-
- const updates = {
- id: user.id,
- username,
- website,
- avatar_url,
- updated_at: new Date(),
- }
-
- let { error } = await supabase.from('profiles').upsert(updates, {
- returning: 'minimal', // Don't return the value after inserting
- })
-
- if (error) throw error
- } catch (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) {
- alert(error.message)
- } finally {
- loading = false
- }
- }
+```ts title="src/hooks.server.ts"
+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.
+
+```html title="src/routes/Auth.svelte"
+<script lang="ts">
+ import { supabaseClient } from '$lib/supabaseClient'
+
+ let loading = false
+ let email: string
+
+ const handleLogin = async () => {
+ try {
+ loading = true
+ const { error } = await supabaseClient.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
- use:getProfile
- class="form-widget"
- on:submit|preventDefault="{updateProfile}"
->
- <div>
- <label for="email">Email</label>
- <input id="email" type="text" value="{$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 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 we can allow them to edit their profile details and manage their account.
+Let's create a new component for that called `Account.svelte`.
+
+```html title="src/routes/Account.svelte"
+<script lang="ts">
+ import { onMount } from 'svelte'
+ import type { AuthSession } from '@supabase/supabase-js'
+ import { supabaseClient } 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 supabaseClient
+ .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 supabaseClient.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 supabaseClient.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>
```
@@ -232,25 +306,21 @@ Now that we have all the components in place, let's update `src/routes/+page.sve
```html title="src/routes/+page.svelte"
<script>
- import { user } from '$lib/sessionStore'
- import { supabase } from '$lib/supabaseClient'
- import Auth from '$lib/Auth.svelte'
- import Profile from '$lib/Profile.svelte'
-
- user.set(supabase.auth.user())
-
- supabase.auth.onAuthStateChange((_, session) => {
- user.set(session.user)
- })
+ import { page } from '$app/stores'
+ import Account from './Account.svelte'
+ import Auth from './Auth.svelte'
</script>
-<div class="container" style="padding: 50px 0 100px 0;">
- {#if $user}
- <Profile />
- {:else}
- <Auth />
- {/if}
-</div>
+<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:
@@ -271,89 +341,95 @@ Every Supabase project is configured with [Storage](/docs/guides/storage) for ma
Let's create an avatar for the user so that they can upload a profile photo. We can start by creating a new component:
-```html title="lib/Avatar.svelte"
-<script>
- import { createEventDispatcher } from 'svelte'
- import { supabase } from '$lib/supabaseClient'
-
- export let path
- export let size = '10em'
-
- let uploading = false
- let src
- let files
-
- const dispatch = createEventDispatcher()
-
- function downloadImage() {
- supabase.storage
- .from('avatars')
- .download(path)
- .then(({ data, error }) => {
- if (error) throw error
- src = URL.createObjectURL(data)
- })
- .catch((error) =>
- console.error('Error downloading image: ', error.message)
- )
- }
-
- async function uploadAvatar() {
- 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 fileName = `${Math.random()}.${fileExt}`
- const filePath = `${fileName}`
-
- let { error: uploadError } = await supabase.storage
- .from('avatars')
- .upload(filePath, file)
-
- if (uploadError) throw uploadError
-
- path = filePath
- dispatch('upload')
- } catch (error) {
- alert(error.message)
- } finally {
- uploading = false
- }
- }
+```html title="src/routes/Avatar.svelte"
+<script lang="ts">
+ import { createEventDispatcher } from 'svelte'
+ import { supabaseClient } 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 supabaseClient.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 supabaseClient.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 path}
- <img
- use:downloadImage
- {src}
- alt="Avatar"
- class="avatar image"
- style="height: {size}; width: {size};"
- />
- {:else}
- <div class="avatar no-image" style="height: {size}; width: {size};" />
- {/if}
-
- <div style="width: {size};">
- <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>
+ {#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>
```
@@ -361,10 +437,10 @@ Let's create an avatar for the user so that they can upload a profile photo. We
And then we can add the widget to the Account page:
-```html title="$lib/Profile.svelte"
+```html title="src/routes/Account.svelte"
<script>
// Import the new component
- import Avatar from '$lib/Avatar.svelte'
+ import Avatar from './Avatar.svelte'
</script>
<form
@@ -373,7 +449,7 @@ And then we can add the widget to the Account page:
on:submit|preventDefault="{updateProfile}"
>
<!-- Add to body -->
- <Avatar bind:path="{avatar_url}" on:upload="{updateProfile}" />
+ <Avatar bind:url={avatarUrl} size={10} on:upload={updateProfile} />
<!-- Other form elements -->
</form>