mirror of
https://github.com/supabase/supabase.git
synced 2026-07-06 13:44:23 +08:00
* docs: update sveltekit tutorial with new @supabase/ssr package Related to issue #21851: Sveltekit guide still uses the old packages * fix comment --------- Co-authored-by: Charis <26616127+charislam@users.noreply.github.com>
635 lines
16 KiB
Plaintext
635 lines
16 KiB
Plaintext
---
|
|
title: 'Build a User Management App with SvelteKit'
|
|
description: 'Learn how to use Supabase in your SvelteKit App.'
|
|
---
|
|
|
|
<QuickstartIntro />
|
|
|
|

|
|
|
|
<Admonition type="note">
|
|
|
|
If you get stuck while working through this guide, refer to the [full example on GitHub](https://github.com/supabase/supabase/tree/master/examples/user-management/sveltekit-user-management).
|
|
|
|
</Admonition>
|
|
|
|
<ProjectSetup />
|
|
|
|
## Building the app
|
|
|
|
Let's start building the Svelte app from scratch.
|
|
|
|
### Initialize a Svelte app
|
|
|
|
We can use the [SvelteKit Skeleton Project](https://kit.svelte.dev/docs) to initialize an app called `supabase-sveltekit` (for this tutorial we will be using TypeScript):
|
|
|
|
```bash
|
|
npm create svelte@latest supabase-sveltekit
|
|
cd supabase-sveltekit
|
|
npm install
|
|
```
|
|
|
|
Then install the Supabase client library: [supabase-js](https://github.com/supabase/supabase-js)
|
|
|
|
```bash
|
|
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](#get-the-api-keys).
|
|
|
|
```bash .env
|
|
PUBLIC_SUPABASE_URL="YOUR_SUPABASE_URL"
|
|
PUBLIC_SUPABASE_ANON_KEY="YOUR_SUPABASE_KEY"
|
|
```
|
|
|
|
Optionally, add `src/styles.css` with the [CSS from the example](https://raw.githubusercontent.com/supabase/supabase/master/examples/user-management/sveltekit-user-management/src/styles.css).
|
|
|
|
### Creating a Supabase client for SSR:
|
|
|
|
The ssr package configures Supabase to use Cookies, which is required for server-side languages and frameworks.
|
|
|
|
Install the Supabase packages:
|
|
|
|
```bash
|
|
npm install @supabase/ssr @supabase/supabase-js
|
|
```
|
|
|
|
Creating a Supabase client with the ssr package automatically configures it to use Cookies. This means your user's session is available throughout the entire SvelteKit stack - page, layout, server, hooks.
|
|
|
|
Add the code below to your `src/hooks.server.ts` to initialize the client on the server:
|
|
|
|
```ts src/hooks.server.ts
|
|
// src/hooks.server.ts
|
|
import { PUBLIC_SUPABASE_URL, PUBLIC_SUPABASE_ANON_KEY } from '$env/static/public'
|
|
import { createServerClient } from '@supabase/ssr'
|
|
import type { Handle } from '@sveltejs/kit'
|
|
|
|
export const handle: Handle = async ({ event, resolve }) => {
|
|
event.locals.supabase = createServerClient(PUBLIC_SUPABASE_URL, PUBLIC_SUPABASE_ANON_KEY, {
|
|
cookies: {
|
|
get: (key) => event.cookies.get(key),
|
|
/**
|
|
* Note: You have to add the `path` variable to the
|
|
* set and remove method due to sveltekit's cookie API
|
|
* requiring this to be set, setting the path to `/`
|
|
* will replicate previous/standard behaviour (https://kit.svelte.dev/docs/types#public-types-cookies)
|
|
*/
|
|
set: (key, value, options) => {
|
|
event.cookies.set(key, value, { ...options, path: '/' })
|
|
},
|
|
remove: (key, options) => {
|
|
event.cookies.delete(key, { ...options, path: '/' })
|
|
},
|
|
},
|
|
})
|
|
|
|
/**
|
|
* A convenience helper so we can just call await getSession() instead const { data: { session } } = await supabase.auth.getSession()
|
|
*/
|
|
event.locals.getSession = async () => {
|
|
const {
|
|
data: { session },
|
|
} = await event.locals.supabase.auth.getSession()
|
|
return session
|
|
}
|
|
|
|
return resolve(event, {
|
|
filterSerializedResponseHeaders(name) {
|
|
return name === 'content-range'
|
|
},
|
|
})
|
|
}
|
|
```
|
|
|
|
<GetSessionWarning />
|
|
|
|
In this case, the session information from `getSession` is supplied to the Supabase client so it can retrieve the auth token. This is safe, since the auth token signature will be revalidated on the Auth server. But you shouldn't trust the unsigned data that is stored alongside the JWT.
|
|
|
|
If you are using TypeScript the compiler might complain about `event.locals.supabase` and `event.locals.getSession`, this can be fixed by updating your `src/app.d.ts` with the content below:
|
|
|
|
```ts src/app.d.ts
|
|
// src/app.d.ts
|
|
|
|
import { SupabaseClient, Session } from '@supabase/supabase-js'
|
|
|
|
declare global {
|
|
namespace App {
|
|
interface Locals {
|
|
supabase: SupabaseClient
|
|
getSession(): Promise<Session | null>
|
|
}
|
|
interface PageData {
|
|
session: Session | null
|
|
}
|
|
// interface Error {}
|
|
// interface Platform {}
|
|
}
|
|
}
|
|
```
|
|
|
|
Create a new `src/routes/+layout.server.ts` file to handle the session on the server-side.
|
|
|
|
```ts src/routes/+layout.server.ts
|
|
// src/routes/+layout.server.ts
|
|
import type { LayoutServerLoad } from './$types'
|
|
|
|
export const load: LayoutServerLoad = async ({ locals: { getSession } }) => {
|
|
return {
|
|
session: await getSession(),
|
|
}
|
|
}
|
|
```
|
|
|
|
> Start your dev server (`npm run dev`) in order to generate the `./$types` files we are referencing in our project.
|
|
|
|
Create a new `src/routes/+layout.ts` file to handle the session and the supabase object on the client-side.
|
|
|
|
```ts src/routes/+layout.ts
|
|
// src/routes/+layout.ts
|
|
import { PUBLIC_SUPABASE_ANON_KEY, PUBLIC_SUPABASE_URL } from '$env/static/public'
|
|
import type { LayoutLoad } from './$types'
|
|
import { createBrowserClient, isBrowser, parse } from '@supabase/ssr'
|
|
|
|
export const load: LayoutLoad = async ({ fetch, data, depends }) => {
|
|
depends('supabase:auth')
|
|
|
|
const supabase = createBrowserClient(PUBLIC_SUPABASE_URL, PUBLIC_SUPABASE_ANON_KEY, {
|
|
global: {
|
|
fetch,
|
|
},
|
|
cookies: {
|
|
get(key) {
|
|
if (!isBrowser()) {
|
|
return JSON.stringify(data.session)
|
|
}
|
|
|
|
const cookie = parse(document.cookie)
|
|
return cookie[key]
|
|
},
|
|
},
|
|
})
|
|
|
|
const {
|
|
data: { session },
|
|
} = await supabase.auth.getSession()
|
|
|
|
return { supabase, session }
|
|
}
|
|
```
|
|
|
|
Update your `src/routes/+layout.svelte`:
|
|
|
|
```svelte src/routes/+layout.svelte
|
|
<!-- src/routes/+layout.svelte -->
|
|
<script lang="ts">
|
|
import '../styles.css'
|
|
import { invalidate } from '$app/navigation'
|
|
import { onMount } from 'svelte'
|
|
|
|
export let data
|
|
|
|
let { supabase, session } = data
|
|
$: ({ supabase, session } = data)
|
|
|
|
onMount(() => {
|
|
const { data } = supabase.auth.onAuthStateChange((event, _session) => {
|
|
if (_session?.expires_at !== session?.expires_at) {
|
|
invalidate('supabase:auth')
|
|
}
|
|
})
|
|
|
|
return () => data.subscription.unsubscribe()
|
|
})
|
|
</script>
|
|
|
|
<svelte:head>
|
|
<title>User Management</title>
|
|
</svelte:head>
|
|
|
|
<div class="container" style="padding: 50px 0 100px 0">
|
|
<slot />
|
|
</div>
|
|
```
|
|
|
|
### Set up a login page
|
|
|
|
#### Supabase Auth UI
|
|
|
|
We can use the [Supabase Auth UI](/docs/guides/auth/auth-helpers/auth-ui), a pre-built Svelte component, for authenticating users via OAuth, email, and magic links.
|
|
|
|
Install the Supabase Auth UI for Svelte
|
|
|
|
```bash
|
|
npm install @supabase/auth-ui-svelte @supabase/auth-ui-shared
|
|
```
|
|
|
|
Add the `Auth` component to your home page
|
|
|
|
```svelte src/routes/+page.svelte
|
|
<!-- src/routes/+page.svelte -->
|
|
<script lang="ts">
|
|
import { Auth } from '@supabase/auth-ui-svelte'
|
|
import { ThemeSupa } from '@supabase/auth-ui-shared'
|
|
|
|
export let data
|
|
</script>
|
|
|
|
<svelte:head>
|
|
<title>User Management</title>
|
|
</svelte:head>
|
|
|
|
<div class="row flex-center flex">
|
|
<div class="col-6 form-widget">
|
|
<Auth
|
|
supabaseClient={data.supabase}
|
|
view="magic_link"
|
|
redirectTo={`${data.url}/auth/callback`}
|
|
showLinks={false}
|
|
appearance={{ theme: ThemeSupa, style: { input: 'color: #fff' } }}
|
|
/>
|
|
</div>
|
|
</div>
|
|
```
|
|
|
|
Create a `src/routes/+page.server.ts` file that will return our website URL to be used in our `redirectTo` above.
|
|
|
|
```ts
|
|
// src/routes/+page.server.ts
|
|
import { redirect } from '@sveltejs/kit'
|
|
import type { PageServerLoad } from './$types'
|
|
|
|
export const load: PageServerLoad = async ({ url, locals: { getSession } }) => {
|
|
const session = await getSession()
|
|
|
|
// if the user is already logged in return them to the account page
|
|
if (session) {
|
|
throw redirect(303, '/account')
|
|
}
|
|
|
|
return { url: url.origin }
|
|
}
|
|
```
|
|
|
|
### Proof Key for Code Exchange (PKCE)
|
|
|
|
As we are employing Proof Key for Code Exchange (PKCE) in our authentication flow, it is necessary to create a server endpoint responsible for exchanging the code for a session.
|
|
|
|
In the following code snippet, we perform the following steps:
|
|
|
|
- Retrieve the code sent back from the Supabase Auth server using the `code` query parameter.
|
|
- Exchange this code for a session, which we store in our chosen storage mechanism (in this case, cookies).
|
|
- Finally, we redirect the user to the `account` page.
|
|
|
|
<Tabs
|
|
scrollable
|
|
size="small"
|
|
type="underlined"
|
|
defaultActiveId="js"
|
|
queryGroup="language"
|
|
>
|
|
<TabPanel id="js" label="JavaScript">
|
|
|
|
```js title=src/routes/auth/callback/+server.js
|
|
// src/routes/auth/callback/+server.js
|
|
import { redirect } from '@sveltejs/kit'
|
|
|
|
export const GET = async ({ url, locals: { supabase } }) => {
|
|
const code = url.searchParams.get('code')
|
|
|
|
if (code) {
|
|
await supabase.auth.exchangeCodeForSession(code)
|
|
}
|
|
|
|
throw redirect(303, '/account')
|
|
}
|
|
```
|
|
|
|
</TabPanel>
|
|
<TabPanel id="ts" label="TypeScript">
|
|
|
|
```ts title=src/routes/auth/callback/+server.ts
|
|
// src/routes/auth/callback/+server.ts
|
|
import { redirect } from '@sveltejs/kit'
|
|
|
|
export const GET = async ({ url, locals: { supabase } }) => {
|
|
const code = url.searchParams.get('code')
|
|
|
|
if (code) {
|
|
await supabase.auth.exchangeCodeForSession(code)
|
|
}
|
|
|
|
throw redirect(303, '/account')
|
|
}
|
|
```
|
|
|
|
</TabPanel>
|
|
</Tabs>
|
|
|
|
### Account page
|
|
|
|
After a user is signed in, they need to be able to edit their profile details and manage their account.
|
|
Create a new `src/routes/account/+page.svelte` file with the content below.
|
|
|
|
```svelte src/routes/account/+page.svelte
|
|
<!-- src/routes/account/+page.svelte -->
|
|
<script lang="ts">
|
|
import { enhance } from '$app/forms';
|
|
import type { SubmitFunction } from '@sveltejs/kit';
|
|
|
|
export let data
|
|
export let form
|
|
|
|
let { session, supabase, profile } = data
|
|
$: ({ session, supabase, profile } = data)
|
|
|
|
let profileForm: HTMLFormElement
|
|
let loading = false
|
|
let fullName: string = profile?.full_name ?? ''
|
|
let username: string = profile?.username ?? ''
|
|
let website: string = profile?.website ?? ''
|
|
let avatarUrl: string = profile?.avatar_url ?? ''
|
|
|
|
const handleSubmit: SubmitFunction = () => {
|
|
loading = true
|
|
return async () => {
|
|
loading = false
|
|
}
|
|
}
|
|
|
|
const handleSignOut: SubmitFunction = () => {
|
|
loading = true
|
|
return async ({ update }) => {
|
|
loading = false
|
|
update()
|
|
}
|
|
}
|
|
</script>
|
|
|
|
<div class="form-widget">
|
|
<form
|
|
class="form-widget"
|
|
method="post"
|
|
action="?/update"
|
|
use:enhance={handleSubmit}
|
|
bind:this={profileForm}
|
|
>
|
|
<div>
|
|
<label for="email">Email</label>
|
|
<input id="email" type="text" value={session.user.email} disabled />
|
|
</div>
|
|
|
|
<div>
|
|
<label for="fullName">Full Name</label>
|
|
<input id="fullName" name="fullName" type="text" value={form?.fullName ?? fullName} />
|
|
</div>
|
|
|
|
<div>
|
|
<label for="username">Username</label>
|
|
<input id="username" name="username" type="text" value={form?.username ?? username} />
|
|
</div>
|
|
|
|
<div>
|
|
<label for="website">Website</label>
|
|
<input id="website" name="website" type="url" value={form?.website ?? website} />
|
|
</div>
|
|
|
|
<div>
|
|
<input
|
|
type="submit"
|
|
class="button block primary"
|
|
value={loading ? 'Loading...' : 'Update'}
|
|
disabled={loading}
|
|
/>
|
|
</div>
|
|
</form>
|
|
|
|
<form method="post" action="?/signout" use:enhance={handleSignOut}>
|
|
<div>
|
|
<button class="button block" disabled={loading}>Sign Out</button>
|
|
</div>
|
|
</form>
|
|
</div>
|
|
```
|
|
|
|
Now create the associated `src/routes/account/+page.server.ts` file that will handle loading our data from the server through the `load` function
|
|
and handle all our form actions through the `actions` object.
|
|
|
|
```ts
|
|
import { fail, redirect } from '@sveltejs/kit'
|
|
import type { Actions, PageServerLoad } from './$types'
|
|
|
|
export const load: PageServerLoad = async ({ locals: { supabase, getSession } }) => {
|
|
const session = await getSession()
|
|
|
|
if (!session) {
|
|
throw redirect(303, '/')
|
|
}
|
|
|
|
const { data: profile } = await supabase
|
|
.from('profiles')
|
|
.select(`username, full_name, website, avatar_url`)
|
|
.eq('id', session.user.id)
|
|
.single()
|
|
|
|
return { session, profile }
|
|
}
|
|
|
|
export const actions: Actions = {
|
|
update: async ({ request, locals: { supabase, getSession } }) => {
|
|
const formData = await request.formData()
|
|
const fullName = formData.get('fullName') as string
|
|
const username = formData.get('username') as string
|
|
const website = formData.get('website') as string
|
|
const avatarUrl = formData.get('avatarUrl') as string
|
|
|
|
const session = await getSession()
|
|
|
|
const { error } = await supabase.from('profiles').upsert({
|
|
id: session?.user.id,
|
|
full_name: fullName,
|
|
username,
|
|
website,
|
|
avatar_url: avatarUrl,
|
|
updated_at: new Date(),
|
|
})
|
|
|
|
if (error) {
|
|
return fail(500, {
|
|
fullName,
|
|
username,
|
|
website,
|
|
avatarUrl,
|
|
})
|
|
}
|
|
|
|
return {
|
|
fullName,
|
|
username,
|
|
website,
|
|
avatarUrl,
|
|
}
|
|
},
|
|
signout: async ({ locals: { supabase, getSession } }) => {
|
|
const session = await getSession()
|
|
if (session) {
|
|
await supabase.auth.signOut()
|
|
throw redirect(303, '/')
|
|
}
|
|
},
|
|
}
|
|
```
|
|
|
|
### Launch!
|
|
|
|
Now that we have all the pages in place, run this in a terminal window:
|
|
|
|
```bash
|
|
npm run dev
|
|
```
|
|
|
|
And then open the browser to [localhost:5173](http://localhost:5173) and you should see the completed app.
|
|
|
|

|
|
|
|
## Bonus: Profile photos
|
|
|
|
Every Supabase project is configured with [Storage](/docs/guides/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/account` directory:
|
|
|
|
```svelte src/routes/account/Avatar.svelte
|
|
<!-- src/routes/account/Avatar.svelte -->
|
|
<script lang="ts">
|
|
import type { SupabaseClient } from '@supabase/supabase-js'
|
|
import { createEventDispatcher } from 'svelte'
|
|
|
|
export let size = 10
|
|
export let url: string
|
|
export let supabase: SupabaseClient
|
|
|
|
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}`
|
|
|
|
const { error } = await supabase.storage.from('avatars').upload(filePath, file)
|
|
|
|
if (error) {
|
|
throw error
|
|
}
|
|
|
|
url = filePath
|
|
setTimeout(() => {
|
|
dispatch('upload')
|
|
}, 100)
|
|
} 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}
|
|
<input type="hidden" name="avatarUrl" value={url} />
|
|
|
|
<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:
|
|
|
|
```svelte src/routes/account/+page.svelte
|
|
<!-- src/routes/account/+page.svelte -->
|
|
<script lang="ts">
|
|
// Import the new component
|
|
import Avatar from './Avatar.svelte'
|
|
</script>
|
|
|
|
<div class="form-widget">
|
|
<form
|
|
class="form-widget"
|
|
method="post"
|
|
action="?/update"
|
|
use:enhance={handleSubmit}
|
|
bind:this={profileForm}
|
|
>
|
|
<!-- Add to body -->
|
|
<Avatar
|
|
{supabase}
|
|
bind:url={avatarUrl}
|
|
size={10}
|
|
on:upload={() => {
|
|
profileForm.requestSubmit();
|
|
}}
|
|
/>
|
|
|
|
<!-- Other form elements -->
|
|
</form>
|
|
</div>
|
|
```
|
|
|
|
At this stage you have a fully functional application!
|