Skip to content

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

Update docs to match latest SvelteKit auth helpers

Andrew Smith42abed370d93
diff --git a/apps/docs/docs/guides/auth/auth-helpers/sveltekit.mdx b/apps/docs/docs/guides/auth/auth-helpers/sveltekit.mdx
index f8267ea371c..62ed1502e16 100644
--- a/apps/docs/docs/guides/auth/auth-helpers/sveltekit.mdx
+++ b/apps/docs/docs/guides/auth/auth-helpers/sveltekit.mdx
@@ -53,152 +53,123 @@ PUBLIC_SUPABASE_ANON_KEY=your-anon-key
Start off by creating a `db.ts` file inside of the `src/lib` directory and instantiate the `supabaseClient`.
```ts title=src/lib/db.ts
-import { createClient } from '@supabase/supabase-js'
-import { setupSupabaseHelpers } from '@supabase/auth-helpers-sveltekit'
-import { dev } from '$app/environment'
-import { env } from '$env/dynamic/public'
+import { createClient } from '@supabase/auth-helpers-sveltekit';
+import { env } from '$env/dynamic/public';
// or use the static env
// import { PUBLIC_SUPABASE_URL, PUBLIC_SUPABASE_ANON_KEY } from '$env/static/public';
-export const supabaseClient = createClient(env.PUBLIC_SUPABASE_URL, env.PUBLIC_SUPABASE_ANON_KEY, {
- persistSession: false,
- autoRefreshToken: false,
-})
-
-setupSupabaseHelpers({
- supabaseClient,
- cookieOptions: {
- secure: !dev,
- },
-})
+export const supabaseClient = createClient(
+ env.PUBLIC_SUPABASE_URL,
+ env.PUBLIC_SUPABASE_ANON_KEY
+);
```
-### Initialize the client
+To make sure the client is initialized on the server and the client we include this file in `src/hooks.server.js` and `src/hooks.client.js`:
-Edit your `+layout.svelte` file and set up the client-side.
+```ts
+import '$lib/db';
+```
-```html title=src/routes/+layout.svelte
-<script lang="ts">
- // make sure the supabase instance is initialized on the client
- import '$lib/db'
- import { startSupabaseSessionSync } from '@supabase/auth-helpers-sveltekit'
- import { page } from '$app/stores'
- import { invalidateAll } from '$app/navigation'
+### Synchronizing the page store
- // this sets up automatic token refreshing
- startSupabaseSessionSync({
- page,
- handleRefresh: () => invalidateAll(),
- })
+Edit your `+layout.svelte` file and set up the client side.
+
+```html
+<!-- src/routes/+layout.svelte -->
+<script>
+ import { supabaseClient } from '$lib/db';
+ import { invalidate } from '$app/navigation';
+ import { onMount } from 'svelte';
+
+ onMount(() => {
+ const {
+ data: { subscription }
+ } = supabaseClient.auth.onAuthStateChange(() => {
+ invalidate('supabase:auth');
+ });
+
+ return () => {
+ subscription.unsubscribe();
+ };
+ });
</script>
<slot />
```
-### Set up hooks
+Every `PageLoad` or `LayoutLoad` using `getSupabase()` will update when `invalidate('supabase:auth')` is called.
-The `hooks.server.ts` file is where the heavy lifting of this library happens:
+If some data is not updated on signin/signout you can fall back to `invalidateAll()`.
-```ts title=src/hooks.server.ts
-// make sure the supabase instance is initialized on the server
-import '$lib/db'
-import { dev } from '$app/environment'
-import { auth } from '@supabase/auth-helpers-sveltekit/server'
+### Send session to client
-export const handle = auth()
+In order to make the session available to the UI (pages, layouts) we need to pass the session in the root layout server load function:
-// use the sequence helper if you have additional Handle methods
-import { sequence } from '@sveltejs/kit/hooks'
+```ts
+// src/routes/+layout.server.ts
+import type { LayoutServerLoad } from './$types';
+import { getServerSession } from '@supabase/auth-helpers-sveltekit';
-export const handle = sequence(auth(), yourHandler)
+export const load: LayoutServerLoad = async (event) => {
+ return {
+ session: await getServerSession(event)
+ };
+};
```
-There are three handle methods available:
-
-- `callback()`:
- This creates a handler for `/api/auth/callback`. The `client` forwards the session details here every time `onAuthStateChange` fires on the client-side. This is needed to set up the cookies for your application so that SSR works seamlessly.
-- `session()`:
- This parses the session from the cookie and populate it in locals
-- `auth()`:
- a shorthand for `sequence(callback(), session())` that uses both handlers
+In addition you can create a layout load function if you are using `invalidate('supabase:auth')`:
-### Send session to client
-
-In order to make the session available to the UI (e.g., pages and layouts), pass the session in the root layout load function:
-
-```ts title=src/routes/+layout.server.ts
-import type { LayoutServerLoad } from './$types'
-
-export const load: LayoutServerLoad = async ({ locals }) => {
- return {
- session: locals.session,
- }
-}
+```ts
+// src/routes/+layout.ts
+import type { LayoutLoad } from './$types';
+import { getSupabase } from '@supabase/auth-helpers-sveltekit';
+
+export const load: LayoutLoad = async (event) => {
+ const { session } = await getSupabase(event);
+ return { session };
+};
```
+This results in less server calls as the client manages the session on it's own.
+
### Typings
-In order to get the most out of TypeScript and IntelliSense, import the types into the `app.d.ts` type definition file that comes with your SvelteKit project.
+In order to get the most out of TypeScript and it´s intellisense, you should import our types into the `app.d.ts` type definition file that comes with your SvelteKit project.
+
+```ts
+// src/app.d.ts
-```ts title=src/app.d.ts
/// <reference types="@sveltejs/kit" />
// See https://kit.svelte.dev/docs/types#app
// for information about these interfaces
// and what to do when importing types
declare namespace App {
- interface Locals {
- session: import('@supabase/auth-helpers-sveltekit').SupabaseSession
+ interface Supabase {
+ Database: import('./DatabaseDefinitions').Database;
+ SchemaName: 'public';
}
+
+ // interface Locals {}
interface PageData {
- session: import('@supabase/auth-helpers-sveltekit').SupabaseSession
+ session: import('@supabase/supabase-js').Session | null;
}
// interface Error {}
// interface Platform {}
}
```
-### Signing out
-
-This library has provided a method to delete the session cookie.
-
-Create a server only page with an action to delete the cookie
-
-```ts title=src/routes/logout/+page.server.ts
-import { deleteSession } from '@supabase/auth-helpers-sveltekit/server'
-import { redirect } from '@sveltejs/kit'
-import type { Actions } from './$types'
-
-export const actions: Actions = {
- async default({ cookies }) {
- deleteSession(cookies)
- throw redirect(303, '/')
- },
-}
-```
+### Basic Setup
-Then make a **POST** request with a form to the server only page above.
+You can now determine if a user is authenticated on the client-side by checking that the `session` object in `$page.data` is defined.
```html
-<script lang="ts">
- import { enhanceAndInvalidate } from '@supabase/auth-helpers-sveltekit'
-</script>
-
-<form action="/logout" method="post" use:enhanceAndInvalidate>
- <button type="submit">Sign out</button>
-</form>
-```
-
-### Basic setup
-
-You can now determine if a user is authenticated on the client-side by checking that the `user` object in `$page.data.session` is defined.
-
-```html title=src/routes/+page.svelte
+<!-- src/routes/+page.svelte -->
<script>
- import { page } from '$app/stores'
+ import { page } from '$app/stores';
</script>
-{#if !$page.data.session.user}
+{#if !$page.data.session}
<h1>I am not logged in</h1>
{:else}
<h1>Welcome {$page.data.session.user.email}</h1>
@@ -208,25 +179,25 @@ You can now determine if a user is authenticated on the client-side by checking
## Client-side data fetching with RLS
-For [row level security](/docs/learn/auth-deep-dive/auth-row-level-security) to work properly when fetching data client-side, you need to make sure to import the `{ supabaseClient }` from `$lib/db` and only run your query once the user is defined client-side in `$page.data.session`:
+For [row level security](https://supabase.com/docs/learn/auth-deep-dive/auth-row-level-security) to work properly when fetching data client-side, you need to make sure to import the `{ supabaseClient }` from `$lib/db` and only run your query once the session is defined client-side in `$page.data`:
```html
<script>
- import { supabaseClient } from '$lib/db'
- import { page } from '$app/stores'
+ import { supabaseClient } from '$lib/db';
+ import { page } from '$app/stores';
- let loadedData = []
+ let loadedData = [];
async function loadData() {
- const { data } = await supabaseClient.from('test').select('*').limit(20)
- loadedData = data
+ const { data } = await supabaseClient.from('test').select('*').limit(20);
+ loadedData = data;
}
- $: if ($page.data.session.user) {
- loadData()
+ $: if ($page.data.session) {
+ loadData();
}
</script>
-{#if $page.data.session.user}
+{#if $page.data.session}
<p>client-side data fetching with RLS</p>
<pre>{JSON.stringify(loadedData, null, 2)}</pre>
{/if}
@@ -234,11 +205,12 @@ For [row level security](/docs/learn/auth-deep-dive/auth-row-level-security) to
## Server-side data fetching with RLS
-```html title=src/routes/profile/+page.svelte
+```html
+<!-- src/routes/profile/+page.svelte -->
<script>
/** @type {import('./$types').PageData} */
- export let data
- $: ({ user, tableData } = data)
+ export let data;
+ $: ({ user, tableData } = data);
</script>
<div>Protected content for {user.email}</div>
@@ -246,209 +218,524 @@ For [row level security](/docs/learn/auth-deep-dive/auth-row-level-security) to
<pre>{JSON.stringify(user, null, 2)}</pre>
```
-For [row level security](/docs/learn/auth-deep-dive/auth-row-level-security) to work in a server environment, you need to use the `withAuth` helper to check if the user is authenticated. The helper extends the event with `session` and `getSupabaseClient()`:
+For [row level security](https://supabase.com/docs/learn/auth-deep-dive/auth-row-level-security) to work in a server environment, you need to use the `getSupabase` helper to check if the user is authenticated. The helper requires the `event` and returns `session` and `supabaseClient`:
-```ts title=src/routes/profile/+page.ts
+```ts
+// src/routes/profile/+page.ts
import type { PageLoad } from './$types';
-import { withAuth } from '@supabase/auth-helpers-sveltekit';
+import { getSupabase } from '@supabase/auth-helpers-sveltekit';
import { redirect } from '@sveltejs/kit';
-interface TestTable {
- id: string;
- created_at: string;
-}
-
-export const load: PageLoad = withAuth(async ({ getSupabaseClient, session }) => {
- if (!session.user) {
+export const load: PageLoad = async (event) => {
+ const { session, supabaseClient } = await getSupabase(event);
+ if (!session) {
throw redirect(303, '/');
}
- const { data: tableData } = await getSupabaseClient()
- .from<TestTable>('test')
- .select('*');
+ const { data: tableData } = await supabaseClient.from('test').select('*');
return {
user: session.user,
tableData
};
-);
-```
-
-**Caution:**
-
-Always use the instance returned by `getSupabaseClient()` directly!
-
-```ts
-// Bad
-const supabaseClient = getSupabaseClient()
-
-await supabaseClient.from('table1').select()
-await supabaseClient.from('table2').select()
-
-// Good
-await getSupabaseClient().from('table1').select()
-await getSupabaseClient().from('table2').select()
+};
```
## Protecting API routes
Wrap an API Route to check that the user has a valid session. If they're not logged in the session is `null`.
-```ts title=src/routes/api/protected-route/+server.ts
+```ts
+// src/routes/api/protected-route/+server.ts
import type { RequestHandler } from './$types';
-import { withAuth } from '@supabase/auth-helpers-sveltekit';
+import { getSupabase } from '@supabase/auth-helpers-sveltekit';
import { json, redirect } from '@sveltejs/kit';
-interface TestTable {
- id: string;
- created_at: string;
-}
-
-export const GET: RequestHandler = withAuth(async ({ session, getSupabaseClient }) => {
- if (!session.user) {
+export const GET: RequestHandler = async (event) => {
+ const { session, supabaseClient } = await getSupabase(event);
+ if (!session) {
throw redirect(303, '/');
}
- const { data } = await getSupabaseClient()
- .from<TestTable>('test')
- .select('*');
+ const { data } = await supabaseClient.from('test').select('*');
return json({ data });
-);
+};
```
If you visit `/api/protected-route` without a valid session cookie, you will get a 303 response.
## Protecting Actions
-Wrap an Action to check that the user has a valid session. If they're not logged in, the session is `null`.
+Wrap an Action to check that the user has a valid session. If they're not logged in the session is `null`.
-```ts title=src/routes/posts/+page.server.ts
-import type { Actions } from './$types'
-import { withAuth } from '@supabase/auth-helpers-sveltekit'
-import { error, invalid } from '@sveltejs/kit'
+```ts
+// src/routes/posts/+page.server.ts
+import type { Actions } from './$types';
+import { getSupabase } from '@supabase/auth-helpers-sveltekit';
+import { error, invalid } from '@sveltejs/kit';
export const actions: Actions = {
- createPost: withAuth(async ({ session, getSupabaseClient, request }) => {
- if (!session.user) {
+ createPost: async (event) => {
+ const { request } = event;
+ const { session, supabaseClient } = await getSupabase(event);
+ if (!session) {
// the user is not signed in
- throw error(403, { message: 'Unauthorized' })
+ throw error(403, { message: 'Unauthorized' });
}
// we are save, let the user create the post
- const formData = await request.formData()
- const content = formData.get('content')
+ const formData = await request.formData();
+ const content = formData.get('content');
- const { error: createPostError, data: newPost } = await getSupabaseClient()
+ const { error: createPostError, data: newPost } = await supabaseClient
.from('posts')
- .insert({ content })
+ .insert({ content });
if (createPostError) {
return invalid(500, {
- supabaseErrorMessage: createPostError.message,
- })
+ supabaseErrorMessage: createPostError.message
+ });
}
return {
- newPost,
- }
- }),
-}
+ newPost
+ };
+ }
+};
```
If you try to submit a form with the action `?/createPost` without a valid session cookie, you will get a 403 error response.
## Saving and deleting the session
-Use `saveSession` to save the session cookies:
-
```ts
-import type { Actions } from './$types'
-import { supabaseClient } from '$lib/db'
-import { invalid, redirect } from '@sveltejs/kit'
-import { saveSession } from '@supabase/auth-helpers-sveltekit/server'
+import type { Actions } from './$types';
+import { invalid, redirect } from '@sveltejs/kit';
+import { getSupabase } from '@supabase/auth-helpers-sveltekit';
export const actions: Actions = {
- async signin({ request, cookies, url }) {
- const formData = await request.formData()
+ signin: async (event) => {
+ const { request, cookies, url } = event;
+ const { session, supabaseClient } = await getSupabase(event);
+ const formData = await request.formData();
- const email = formData.get('email') as string
- const password = formData.get('password') as string
+ const email = formData.get('email') as string;
+ const password = formData.get('password') as string;
- const { data, error } = await supabaseClient.auth.api.signInWithEmail(email, password, {
- redirectTo: `${url.origin}/logging-in`,
- })
+ const { error } = await supabaseClient.auth.signInWithPassword({
+ email,
+ password
+ });
- if (error || !data) {
- if (error?.status === 400) {
+ if (error) {
+ if (error instanceof AuthApiError && error.status === 400) {
return invalid(400, {
- error: 'Invalid credentials',
+ error: 'Invalid credentials.',
values: {
- email,
- },
- })
+ email
+ }
+ });
}
return invalid(500, {
error: 'Server error. Try again later.',
values: {
- email,
- },
- })
+ email
+ }
+ });
}
- saveSession(cookies, data)
- throw redirect(303, '/dashboard')
+ throw redirect(303, '/dashboard');
},
-}
+
+ signout: async (event) => {
+ const { supabaseClient } = await getSupabase(event);
+ await supabaseClient.auth.signOut();
+ throw redirect(303, '/');
+ }
+};
```
-Use `deleteSession` to delete the session cookies:
+## Protecting multiple routes
+
+To avoid writing the same auth logic in every single route you can use the handle hook to
+protect multiple routes at once.
```ts
-import type { Actions } from './$types'
-import { deleteSession } from '@supabase/auth-helpers-sveltekit/server'
-import { redirect } from '@sveltejs/kit'
+// src/hooks.server.ts
+import type { RequestHandler } from './$types';
+import { getSupabase } from '@supabase/auth-helpers-sveltekit';
+import { redirect, error } from '@sveltejs/kit';
-export const actions: Actions = {
- async logout({ cookies }) {
- deleteSession(cookies)
- throw redirect(303, '/')
+export const handle: Handle = async ({ event, resolve }) => {
+ // protect requests to all routes that start with /protected-routes
+ if (event.url.pathname.startsWith('/protected-routes')) {
+ const { session, supabaseClient } = await getSupabase(event);
+
+ if (!session) {
+ throw redirect(303, '/');
+ }
+ }
+
+ // protect POST requests to all routes that start with /protected-posts
+ if (
+ event.url.pathname.startsWith('/protected-posts') &&
+ event.request.method === 'POST'
+ ) {
+ const { session, supabaseClient } = await getSupabase(event);
+
+ if (!session) {
+ throw error(303, '/');
+ }
+ }
+
+ return resolve(event);
+};
+```
+
+## Migrate from 0.7.x to 0.8 {#migration}
+
+### Set up the Supabase client {#migration-set-up-supabase-client}
+
+<Tabs
+ scrollable
+ size="small"
+ type="underlined"
+ defaultActiveId="older-0.7"
+>
+<TabPanel id="older-0.7" label="0.7.x">
+
+```js title=src/lib/db.ts
+import { createClient } from '@supabase/supabase-js'
+import { setupSupabaseHelpers } from '@supabase/auth-helpers-sveltekit'
+import { dev } from '$app/environment'
+import { env } from '$env/dynamic/public'
+// or use the static env
+
+// import { PUBLIC_SUPABASE_URL, PUBLIC_SUPABASE_ANON_KEY } from '$env/static/public';
+
+export const supabaseClient = createClient(env.PUBLIC_SUPABASE_URL, env.PUBLIC_SUPABASE_ANON_KEY, {
+ persistSession: false,
+ autoRefreshToken: false,
+})
+
+setupSupabaseHelpers({
+ supabaseClient,
+ cookieOptions: {
+ secure: !dev,
},
-}
+})
+```
+
+</TabPanel>
+<TabPanel id="0.8.0" label="0.8.0">
+
+```js title=src/lib/db.ts
+import { createClient } from '@supabase/auth-helpers-sveltekit'
+import { env } from '$env/dynamic/public'
+// or use the static env
+
+// import { PUBLIC_SUPABASE_URL, PUBLIC_SUPABASE_ANON_KEY } from '$env/static/public';
+
+export const supabaseClient = createClient(
+ env.PUBLIC_SUPABASE_URL,
+ env.PUBLIC_SUPABASE_ANON_KEY
+);
+```
+
+</TabPanel>
+</Tabs>
+
+### Initialize the client {#migration-initialize-client}
+
+<Tabs
+ scrollable
+ size="small"
+ type="underlined"
+ defaultActiveId="older-0.7"
+>
+<TabPanel id="older-0.7" label="0.7.x">
+
+```html title=src/routes/+layout.svelte
+<script lang="ts">
+ // make sure the supabase instance is initialized on the client
+ import '$lib/db'
+ import { startSupabaseSessionSync } from '@supabase/auth-helpers-sveltekit'
+ import { page } from '$app/stores'
+ import { invalidateAll } from '$app/navigation'
+
+ // this sets up automatic token refreshing
+ startSupabaseSessionSync({
+ page,
+ handleRefresh: () => invalidateAll(),
+ })
+</script>
+
+<slot />
+```
+
+</TabPanel>
+<TabPanel id="0.8.0" label="0.8.0">
+
+```html title=src/routes/+layout.svelte
+<script>
+ import { supabaseClient } from '$lib/db';
+ import { invalidate } from '$app/navigation';
+ import { onMount } from 'svelte';
+
+ onMount(() => {
+ const {
+ data: { subscription }
+ } = supabaseClient.auth.onAuthStateChange(() => {
+ invalidate('supabase:auth');
+ });
+
+ return () => {
+ subscription.unsubscribe();
+ };
+ });
+</script>
+
+<slot />
```
-## Custom session namespace
+</TabPanel>
+</Tabs>
-If you want to use something other than `locals.session` and `$page.data.session`, update the types and create three helper functions:
+### Set up hooks {#migration-set-up-hooks}
+
+<Tabs
+ scrollable
+ size="small"
+ type="underlined"
+ defaultActiveId="older-0-7"
+>
+<TabPanel id="older-0-7" label="0.7.x">
+
+```ts title=src/hooks.server.ts
+// make sure the supabase instance is initialized on the server
+import '$lib/db'
+import { dev } from '$app/environment'
+import { auth } from '@supabase/auth-helpers-sveltekit/server'
+
+export const handle = auth()
+```
+
+**Optional** _if using additional handle methods_
+
+```ts title=src/hooks.server.ts
+// make sure the supabase instance is initialized on the server
+import '$lib/db'
+import { dev } from '$app/environment'
+import { auth } from '@supabase/auth-helpers-sveltekit/server'
+import { sequence } from '@sveltejs/kit/hooks'
+
+export const handle = sequence(auth(), yourHandler)
+```
+
+</TabPanel>
+<TabPanel id="0.8.0" label="0.8.0">
+
+```ts title=src/hooks.server.ts
+// make sure the supabase instance is initialized on the server
+import '$lib/db'
+```
+
+```ts title=src/hooks.client.ts
+// make sure the supabase instance is initialized on the client
+import '$lib/db'
+```
+
+</TabPanel>
+</Tabs>
+
+### Typings {#migration-typings}
+
+<Tabs
+ scrollable
+ size="small"
+ type="underlined"
+ defaultActiveId="older-0-7"
+>
+<TabPanel id="older-0-7" label="0.7.x">
```ts title=src/app.d.ts
+/// <reference types="@sveltejs/kit" />
+
+// See https://kit.svelte.dev/docs/types#app
+// for information about these interfaces
+// and what to do when importing types
declare namespace App {
interface Locals {
- mySupabaseSession: import('@supabase/auth-helpers-sveltekit').SupabaseSession
+ session: import('@supabase/auth-helpers-sveltekit').SupabaseSession
}
+
interface PageData {
- mySupabaseSession: import('@supabase/auth-helpers-sveltekit').SupabaseSession
+ session: import('@supabase/auth-helpers-sveltekit').SupabaseSession
}
+
+ // interface Error {}
+ // interface Platform {}
}
```
-```ts title=src/hooks.server.ts
-setupSupabaseServer({
- supabaseClient,
- cookieOptions: {
- secure: !dev,
- },
- // --- change location within locals ---
- getSessionFromLocals: (locals) => locals.mySupabaseSession,
- setSessionToLocals: (locals, session) => (locals.mySupabaseSession = session),
-})
+</TabPanel>
+<TabPanel id="0.8.0" label="0.8.0">
+
+```ts title=src/app.d.ts
+/// <reference types="@sveltejs/kit" />
+
+// See https://kit.svelte.dev/docs/types#app
+// for information about these interfaces
+// and what to do when importing types
+declare namespace App {
+ interface Supabase {
+ Database: import('./DatabaseDefinitions').Database;
+ SchemaName: 'public';
+ }
+
+ // interface Locals {}
+ interface PageData {
+ session: import('@supabase/auth-helpers-sveltekit').SupabaseSession;
+ }
+ // interface Error {}
+ // interface Platform {}
+}
```
-```ts title=src/lib/db.ts
-setupSupabaseClient({
- supabaseClient,
- // --- change location within pageData ---
- getSessionFromPageData: (data) => data.mySupabaseSession,
+</TabPanel>
+</Tabs>
+
+### withPageAuth {#migration-with-page-auth}
+
+<Tabs
+ scrollable
+ size="small"
+ type="underlined"
+ defaultActiveId="older-0-7"
+>
+<TabPanel id="older-0-7" label="0.7.x">
+
+```html title=src/routes/protected-route/+page.svelte
+<script lang="ts">
+ import type { PageData } from './$types'
+
+ export let data: PageData
+ $: ({ tableData, user } = data)
+</script>
+
+<div>Protected content for {user.email}</div>
+<p>server-side fetched data with RLS:</p>
+<pre>{JSON.stringify(tableData, null, 2)}</pre>
+<p>user:</p>
+<pre>{JSON.stringify(user, null, 2)}</pre>
+```
+
+```ts title=src/routes/protected-route/+page.ts
+import { withAuth } from '@supabase/auth-helpers-sveltekit'
+import { redirect } from '@sveltejs/kit'
+import type { PageLoad } from './$types'
+
+export const load: PageLoad = withAuth(async ({ session, getSupabaseClient }) => {
+ if (!session.user) {
+ throw redirect(303, '/')
+ }
+
+ const { data: tableData } = await getSupabaseClient().from('test').select('*')
+ return { tableData, user: session.user }
})
```
-## Migrate from 0.6.11 and below to 0.7.0 {#migration}
+</TabPanel>
+<TabPanel id="0.8.0" label="0.8.0">
+
+```html title=src/routes/protected-route/+page.svelte
+<script>
+ /** @type {import('./$types').PageData} */
+ export let data;
+ $: ({ user, tableData } = data);
+</script>
+
+<div>Protected content for {user.email}</div>
+<pre>{JSON.stringify(tableData, null, 2)}</pre>
+<pre>{JSON.stringify(user, null, 2)}</pre>
+```
+
+```ts title=src/routes/protected-route/+page.ts
+// src/routes/profile/+page.ts
+import type { PageLoad } from './$types';
+import { getSupabase } from '@supabase/auth-helpers-sveltekit';
+import { redirect } from '@sveltejs/kit';
+
+export const load: PageLoad = async (event) => {
+ const { session, supabaseClient } = await getSupabase(event);
+ if (!session) {
+ throw redirect(303, '/');
+ }
+ const { data: tableData } = await supabaseClient.from('test').select('*');
+
+ return {
+ user: session.user,
+ tableData
+ };
+};
+```
+
+</TabPanel>
+</Tabs>
+
+### withApiAuth {#migration-with-api-auth}
+
+<Tabs
+ scrollable
+ size="small"
+ type="underlined"
+ defaultActiveId="older-0-7"
+>
+<TabPanel id="older-0-7" label="0.7.x">
+
+```ts title=src/routes/api/protected-route/+server.ts
+import type { RequestHandler } from './$types';
+import { withAuth } from '@supabase/auth-helpers-sveltekit';
+import { json, redirect } from '@sveltejs/kit';
+
+interface TestTable {
+ id: string;
+ created_at: string;
+}
+
+export const GET: RequestHandler = withAuth(async ({ session, getSupabaseClient }) => {
+ if (!session.user) {
+ throw redirect(303, '/');
+ }
+
+ const { data } = await getSupabaseClient()
+ .from<TestTable>('test')
+ .select('*');
+
+ return json({ data });
+});
+```
+
+</TabPanel>
+<TabPanel id="0.8.0" label="0.8.0">
+
+```ts title=src/routes/api/protected-route/+server.ts
+import type { RequestHandler } from './$types';
+import { getSupabase } from '@supabase/auth-helpers-sveltekit';
+import { json, redirect } from '@sveltejs/kit';
+
+export const GET: RequestHandler = async (event) => {
+ const { session, supabaseClient } = await getSupabase(event);
+ if (!session) {
+ throw redirect(303, '/');
+ }
+ const { data } = await supabaseClient.from('test').select('*');
+
+ return json({ data });
+};
+```
+
+</TabPanel>
+</Tabs>
+
+## Migrate from 0.6.11 and below to 0.7.0 {#migration-0-7}
There are numerous breaking changes in the latest 0.7.0 version of this library.
@@ -456,7 +743,7 @@ There are numerous breaking changes in the latest 0.7.0 version of this library.
The environment variable prefix is now `PUBLIC_` instead of `VITE_` (e.g., `VITE_SUPABASE_URL` is now `PUBLIC_SUPABASE_URL`).
-### Set up the Supabase client {#migration-set-up-supabase-client}
+### Set up the Supabase client {#migration-set-up-supabase-client-0-7}
<Tabs
scrollable
@@ -478,7 +765,7 @@ export { supabaseClient };
```
</TabPanel>
-<TabPanel id="latest" label="0.7.0">
+<TabPanel id="0.7.0" label="0.7.0">
```js title=src/lib/db.ts
import { createClient } from '@supabase/supabase-js'
@@ -505,7 +792,7 @@ setupSupabaseHelpers({
</TabPanel>
</Tabs>
-### Initialize the client {#migration-initialize-client}
+### Initialize the client {#migration-initialize-client-0-7}
<Tabs
scrollable
@@ -528,7 +815,7 @@ setupSupabaseHelpers({
```
</TabPanel>
-<TabPanel id="latest" label="0.7.0">
+<TabPanel id="0.7.0" label="0.7.0">
The `@supabase/auth-helpers-svelte` library is no longer required as the `@supabase/auth-helpers-sveltekit` library handles all the client-side code.
@@ -553,7 +840,7 @@ The `@supabase/auth-helpers-svelte` library is no longer required as the `@supab
</TabPanel>
</Tabs>
-### Set up hooks {#migration-set-up-hooks}
+### Set up hooks {#migration-set-up-hooks-0-7}
<Tabs
scrollable
@@ -581,7 +868,7 @@ export const getSession: GetSession = async (event) => {
```
</TabPanel>
-<TabPanel id="latest" label="0.7.0">
+<TabPanel id="0.7.0" label="0.7.0">
```ts title=src/hooks.server.ts
// make sure the supabase instance is initialized on the server
@@ -607,7 +894,7 @@ export const handle = sequence(auth(), yourHandler)
</TabPanel>
</Tabs>
-### Typings {#migration-typings}
+### Typings {#migration-typings-0-7}
<Tabs
scrollable
@@ -639,7 +926,7 @@ declare namespace App {
```
</TabPanel>
-<TabPanel id="latest" label="0.7.0">
+<TabPanel id="0.7.0" label="0.7.0">
```ts title=src/app.d.ts
/// <reference types="@sveltejs/kit" />
@@ -688,7 +975,7 @@ declare namespace App {
```
</TabPanel>
-<TabPanel id="latest" label="0.7.0">
+<TabPanel id="0.7.0" label="0.7.0">
```html title=src/routes/+page.svelte
<script>
@@ -747,7 +1034,7 @@ declare namespace App {
```
</TabPanel>
-<TabPanel id="latest" label="0.7.0">
+<TabPanel id="0.7.0" label="0.7.0">
```html title=src/routes/protected-route/+page.svelte
<script lang="ts">
@@ -818,7 +1105,7 @@ export const GET: RequestHandler<GetOutput> = async ({ locals, request }) =>
```
</TabPanel>
-<TabPanel id="latest" label="0.7.0">
+<TabPanel id="0.7.0" label="0.7.0">
```ts title=src/routes/api/protected-route/+server.ts
import type { RequestHandler } from './$types';