Skip to content

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

Update SvelteKit user management guide with pkce

Andrew Smithccd53a68628a
diff --git a/apps/docs/pages/guides/getting-started/tutorials/with-nextjs.mdx b/apps/docs/pages/guides/getting-started/tutorials/with-nextjs.mdx
index b1048cc5dd6..d54980827e2 100644
--- a/apps/docs/pages/guides/getting-started/tutorials/with-nextjs.mdx
+++ b/apps/docs/pages/guides/getting-started/tutorials/with-nextjs.mdx
@@ -22,8 +22,7 @@ Let's start building the Next.js app from scratch.
### Initialize a Next.js app
-We can use [`create-next-app`](https://nextjs.org/docs/getting-started) to initialize
-an app called `supabase-nextjs`:
+We can use [`create-next-app`](https://nextjs.org/docs/getting-started) to initialize an app called `supabase-nextjs`:
<Tabs
scrollable
diff --git a/apps/docs/pages/guides/getting-started/tutorials/with-sveltekit.mdx b/apps/docs/pages/guides/getting-started/tutorials/with-sveltekit.mdx
index 29cf5bd2385..e36b61ce214 100644
--- a/apps/docs/pages/guides/getting-started/tutorials/with-sveltekit.mdx
+++ b/apps/docs/pages/guides/getting-started/tutorials/with-sveltekit.mdx
@@ -22,8 +22,7 @@ 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):
+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
@@ -118,9 +117,7 @@ Create a new `src/routes/+layout.server.ts` file to handle the session on the se
```ts title=src/routes/+layout.server.ts
// src/routes/+layout.server.ts
-import type { LayoutServerLoad } from './$types'
-
-export const load: LayoutServerLoad = async ({ locals: { getSession } }) => {
+export const load = async ({ locals: { getSession } }) => {
return {
session: await getSession(),
}
@@ -136,9 +133,8 @@ Create a new `src/routes/+layout.ts` file to handle the session and the supabase
import { invalidate } from '$app/navigation'
import { PUBLIC_SUPABASE_ANON_KEY, PUBLIC_SUPABASE_URL } from '$env/static/public'
import { createSupabaseLoadClient } from '@supabase/auth-helpers-sveltekit'
-import type { LayoutLoad } from './$types'
-export const load: LayoutLoad = async ({ fetch, data, depends }) => {
+export const load = async ({ fetch, data, depends }) => {
depends('supabase:auth')
const supabase = createSupabaseLoadClient({
@@ -161,23 +157,24 @@ Update your `src/routes/+layout.svelte`:
```svelte title=src/routes/+layout.svelte
<!-- src/routes/+layout.svelte -->
<script lang="ts">
- import '../styles.css';
- import { invalidate } from '$app/navigation';
- import { onMount } from 'svelte';
+ import '../styles.css'
+ import { invalidate } from '$app/navigation'
+ import { onMount } from 'svelte'
- export let data;
+ export let data
- $: ({ supabase, session } = 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');
+ invalidate('supabase:auth')
}
- });
+ })
- return () => data.subscription.unsubscribe();
- });
+ return () => data.subscription.unsubscribe()
+ })
</script>
<svelte:head>
@@ -206,10 +203,10 @@ Add the `Auth` component to your home page
```svelte title=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';
+ import { Auth } from '@supabase/auth-ui-svelte'
+ import { ThemeSupa } from '@supabase/auth-ui-shared'
- export let data;
+ export let data
</script>
<svelte:head>
@@ -221,7 +218,7 @@ Add the `Auth` component to your home page
<Auth
supabaseClient={data.supabase}
view="magic_link"
- redirectTo={`${data.url}/logging-in?redirect=/`}
+ redirectTo={`${data.url}/auth/callback`}
showLinks={false}
appearance={{ theme: ThemeSupa, style: { input: 'color: #fff' } }}
/>
@@ -231,11 +228,6 @@ Add the `Auth` component to your home page
Create a `src/routes/+page.server.ts` file that will return our website url to be used in our `redirectTo` above.
-> This is necessary because the current Supabase auth flow uses implicit grant which returns the tokens as part of the url fragment (#).
-
-> The redirect to a non server protected page will make sure that the client captures the url fragment as we cannot read these on the server
-> and send it over to the server. This all happens behind the scenes and isn't something you will need to do manually.
-
```ts
// src/routes/+page.server.ts
import { redirect } from '@sveltejs/kit'
@@ -253,37 +245,60 @@ export const load: PageServerLoad = async ({ url, locals: { getSession } }) => {
}
```
-### Loading page
+### Proof Key for Code Exchange (PKCE)
-Create a `src/routes/logging-in/+page.svelte` file with the code below.
+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.
-This page is used for waiting while your client-side code inside of `src/routes/+layout.ts` sends the tokens over to your server-side code to store it in a cookie.
+In the following code snippet, we perform the following steps:
-```svelte
-<!-- src/routes/logging-in/+page.svelte -->
-<script lang="ts">
- import { browser } from '$app/environment';
- import { goto } from '$app/navigation';
- import { page } from '$app/stores';
+- 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.
- export let data;
- $: {
- const redirectTo = $page.url.searchParams.get('redirect');
+<Tabs
+ scrollable
+ size="small"
+ type="underlined"
+ defaultActiveId="js"
+>
+<TabPanel id="js" label="JavaScript">
- // check if user has been set in session store then redirect
- if (browser && data.session) {
- goto(redirectTo ?? '/account');
- }
- }
-</script>
+```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)
+ }
-<section>
- "Because as we know, there are known knowns; there are things we know we know. We also know there
- are known unknowns; that is to say we know there are some things we do not know. But there are
- also unknown unknowns—the ones we don't know we don't know" - Donald Rumsfeld
-</section>
+ 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.
@@ -292,32 +307,33 @@ Create a new `src/routes/account/+page.svelte` file with the content below.
```svelte title=src/routes/account/+page.svelte
<!-- src/routes/account/+page.svelte -->
<script lang="ts">
- import { enhance, type SubmitFunction } from '$app/forms';
+ import { enhance, type SubmitFunction } from '$app/forms'
- export let data;
- export let form;
+ export let data
+ export let form
- let { session, supabase, profile } = data;
+ let { session, supabase, profile } = data
+ $: ({ session, supabase, profile } = data)
- let profileForm: any;
- 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 ?? '';
+ 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;
+ loading = true
return async () => {
- loading = false;
+ loading = false
}
}
const handleSignOut: SubmitFunction = () => {
- loading = true;
+ loading = true
return async ({ update }) => {
- loading = false;
- update();
+ loading = false
+ update()
}
}
</script>
@@ -373,9 +389,8 @@ 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 = (async ({ locals: { supabase, getSession } }) => {
+export const load = async ({ locals: { supabase, getSession } }) => {
const session = await getSession()
if (!session) {
@@ -389,7 +404,7 @@ export const load = (async ({ locals: { supabase, getSession } }) => {
.single()
return { session, profile }
-}) satisfies PageServerLoad
+}
export const actions = {
update: async ({ request, locals: { supabase, getSession } }) => {
@@ -433,7 +448,7 @@ export const actions = {
throw redirect(303, '/')
}
},
-} satisfies Actions
+}
```
### Launch!
@@ -459,65 +474,68 @@ Let's create an avatar for the user so that they can upload a profile photo. We
```svelte title=src/routes/account/Avatar.svelte
<!-- src/routes/account/Avatar.svelte -->
<script lang="ts">
- import type { SupabaseClient } from '@supabase/supabase-js';
- import { createEventDispatcher } from 'svelte';
+ import type { SupabaseClient } from '@supabase/supabase-js'
+ import { createEventDispatcher } from 'svelte'
- export let size = 10;
- export let url: string;
- export let supabase: SupabaseClient;
+ export let size = 10
+ export let url: string
+ export let supabase: SupabaseClient
- let avatarUrl: string | null = null;
- let uploading = false;
- let files: FileList;
+ let avatarUrl: string | null = null
+ let uploading = false
+ let files: FileList
- const dispatch = createEventDispatcher();
+ const dispatch = createEventDispatcher()
const downloadImage = async (path: string) => {
try {
- const { data, error } = await supabase.storage.from('avatars').download(path);
+ const { data, error } = await supabase.storage.from('avatars').download(path)
if (error) {
- throw error;
+ throw error
}
- const url = URL.createObjectURL(data);
- avatarUrl = url;
+ const url = URL.createObjectURL(data)
+ avatarUrl = url
} catch (error) {
if (error instanceof Error) {
- console.log('Error downloading image: ', error.message);
+ console.log('Error downloading image: ', error.message)
}
}
- };
+ }
const uploadAvatar = async () => {
try {
- uploading = true;
+ uploading = true
if (!files || files.length === 0) {
- throw new Error('You must select an image to upload.');
+ throw new Error('You must select an image to upload.')
}
- const file = files[0];
- const fileExt = file.name.split('.').pop();
- url = `${Math.random()}.${fileExt}`;
+ const file = files[0]
+ const fileExt = file.name.split('.').pop()
+ const filePath = `${Math.random()}.${fileExt}`
- let { error } = await supabase.storage.from('avatars').upload(url, file);
+ let { error } = await supabase.storage.from('avatars').upload(filePath, file)
if (error) {
- throw error;
+ throw error
}
- dispatch('upload');
+ url = filePath
+ setTimeout(() => {
+ dispatch('upload')
+ }, 100)
} catch (error) {
if (error instanceof Error) {
- alert(error.message);
+ alert(error.message)
}
} finally {
- uploading = false;
+ uploading = false
}
- };
+ }
- $: if (url) downloadImage(url);
+ $: if (url) downloadImage(url)
</script>
<div>