Skip to content

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

Update with migration guide for SvelteKit RC

Andrew Smith599a4ac392ae
diff --git a/apps/reference/docs/guides/auth/auth-helpers/sveltekit.mdx b/apps/reference/docs/guides/auth/auth-helpers/sveltekit.mdx
index 849c9c5a771..8345b6f5377 100644
--- a/apps/reference/docs/guides/auth/auth-helpers/sveltekit.mdx
+++ b/apps/reference/docs/guides/auth/auth-helpers/sveltekit.mdx
@@ -13,18 +13,12 @@ Using [npm](https://npmjs.org):
```sh
npm install @supabase/auth-helpers-sveltekit
-
-# Main component for Svelte based frameworks (optional but recommended)
-npm install @supabase/auth-helpers-svelte
```
Using [yarn](https://yarnpkg.com/):
```sh
yarn add @supabase/auth-helpers-sveltekit
-
-# Main component for Svelte based frameworks (optional but recommended)
-yarn add @supabase/auth-helpers-svelte
```
This library supports the following tooling versions:
@@ -39,267 +33,747 @@ Set up the fillowing env vars. For local development you can set them in a `.env
```bash
# Find these in your Supabase project settings > API
-VITE_SUPABASE_URL=https://your-project.supabase.co
-VITE_SUPABASE_ANON_KEY=your-anon-key
+PUBLIC_SUPABASE_URL=https://your-project.supabase.co
+PUBLIC_SUPABASE_ANON_KEY=your-anon-key
```
-### SupabaseClient and SupaAuthHelper component setup
+### SupabaseClient setup
-We will start off by creating a `db.ts` file inside of our `src/lib` directory. Now lets instantiate our `supabaseClient` by using our `createSupabaseClient` function from the `@supabase/auth-helpers-sveltekit` library.
+We will start off by creating a `db.ts` file inside of our `src/lib` directory. Now lets instantiate our `supabaseClient`.
```ts
// src/lib/db.ts
-import { createSupabaseClient } from '@supabase/auth-helpers-sveltekit'
-
-const { supabaseClient } = createSupabaseClient(
- import.meta.env.VITE_SUPABASE_URL as string,
- import.meta.env.VITE_SUPABASE_ANON_KEY as string
-)
-
-export { supabaseClient }
+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
+ }
+});
```
-Edit your `__layout.svelte` file and add import the `SupaAuthHelper` component, the `supabaseClient` we just instantiated and the `session` store.
+### Initialize the client
+
+Edit your `+layout.svelte` file and set up the client side.
```html
-// src/routes/__layout.svelte
-<script>
- import { session } from '$app/stores'
- import { supabaseClient } from '$lib/db'
- import { SupaAuthHelper } from '@supabase/auth-helpers-svelte'
+<!-- src/routes/+layout.svelte -->
+<script lang="ts">
+ // we need to make sure the supabase instance is initialized on the client
+ import '$lib/db';
+ import { startSupabaseSessionSync } from '@supabase/auth-helpers-sveltekit';
+
+ // this sets up automatic token refreshing
+ startSupabaseSessionSync();
</script>
-<SupaAuthHelper {supabaseClient} {session}>
- <slot />
-</SupaAuthHelper>
+<slot />
```
### Hooks setup
-Our `hooks.ts` file is where the heavy lifting of this library happens, we need to import our function to handle the sign in, signing out and cookie creation phase. we can import all the hooks using `handleAuth` function and destructure its returned data.
+Our `hooks.ts` file is where the heavy lifting of this library happens:
```ts
-// src/hooks.ts
-import { handleAuth } from '@supabase/auth-helpers-sveltekit'
-import type { GetSession, Handle } from '@sveltejs/kit'
-import { sequence } from '@sveltejs/kit/hooks'
+// src/hooks.server.ts
-export const handle: Handle = sequence(...handleAuth())
+// we need to 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 getSession: GetSession = async (event) => {
- const { user, accessToken, error } = event.locals
- return {
- user,
- accessToken,
- error,
- }
-}
+export const handle = auth();
+
+// use the sequence helper if you have additional Handle methods
+import { sequence } from '@sveltejs/kit/hooks';
+
+export const handle = sequence(auth(), yourHandler);
```
-These will create the handlers under the hood that perform different parts of the authentication flow:
+There are three handle methods available:
+
+- `callback()`:
+ This will create 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 will parse the session from the cookie and populate it in locals
+- `auth()`:
+ a shorthand for `sequence(callback(), session())` that uses both handlers
+
+### Send session to client
+
+In order to make the session available to the UI (pages, layouts) we need to pass the session in the root layout load function:
+
+```ts
+// src/routes/+layout.server.ts
+import type { LayoutServerLoad } from './$types';
-- `/api/auth/callback`: The `UserHelper` 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.
-- `/api/auth/user`: You can fetch user profile information in JSON format.
-- `/api/auth/logout`: You can logout the user.
+export const load: LayoutServerLoad = async ({ locals }) => {
+ return {
+ session: locals.session
+ };
+};
+```
### Typings
-In order to get the most out of TypeScript and its intellisense, you should import our 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
/// <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 UserSession {
- user: import('@supabase/supabase-js').User
- accessToken?: string
+ interface Locals {
+ session: import('@supabase/auth-helpers-sveltekit').SupabaseSession;
}
- interface Locals extends UserSession {
- error: import('@supabase/supabase-js').ApiError
+ interface PageData {
+ session: import('@supabase/auth-helpers-sveltekit').SupabaseSession;
}
-
- interface Session extends UserSession {} // interface Platform {} // interface Stuff {}
+ // interface Error {}
+ // interface Platform {}
}
```
### Signing out
-This library has provided a dedicated endpoint for you to use to sign a user out. This endpoint will sign the user out of the Gotrue server, clear the cookies that were set when the user logged in and redirect the user to a configurable path.
+This library has provided a method to delete the session cookie.
-The logout handler endpoint is `/api/auth/logout`, this will take a `GET` request which means it can be used as the href for a normal `a` tag in your html.
+Create a server only page with an action to delete the cookie
-```html
-<a href="/api/auth/logout">Sign out</a>
+```ts
+// 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, '/');
+ }
+};
```
+Then make a **POST** request with a form to the server only page above.
-### Logout handler configuration
-
-In your `src/hooks.ts` file the logout handler is already setup and you can configure the redirect path from here.
-
-> By default the redirect path after logging out will be `/`.
+```html
+<script lang="ts">
+ import { enhanceAndInvalidate } from '@supabase/auth-helpers-sveltekit';
+</script>
-```ts
-export const handle = sequence(
- ...handleAuth({
- logout: { returnTo: '/auth/signin' },
- })
-)
+<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 returned by the `$session` store is defined.
+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
-// example
+<!-- src/routes/+page.svelte -->
<script>
- import { session } from '$app/stores'
+ import { page } from '$app/stores';
</script>
-{#if !$session.user}
-<h1>I am not logged in</h1>
+{#if !$page.data.session.user}
+ <h1>I am not logged in</h1>
{:else}
-<h1>Welcome {$session.user.email}</h1>
-<p>I am logged in!</p>
+ <h1>Welcome {$page.data.session.user.email}</h1>
+ <p>I am logged in!</p>
{/if}
```
## Client-side data fetching with RLS
-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 `@supabase/auth-helpers-sveltekit` and only run your query once the user is defined client-side in the `$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 user is defined client-side in `$page.data.session`:
```html
<script>
-import Auth from 'supabase-ui-svelte';
-import { error, isLoading } from '@supabase/auth-helpers-svelte';
-import { supabaseClient } from '$lib/db';
-import { session } from '$app/stores';
+ import { supabaseClient } from '$lib/db';
+ import { page } from '$app/stores';
-let loadedData = [];
-async function loadData() {
- const { data } = await supabaseClient.from('test').select('*').single();
- loadedData = data
-}
+ let loadedData = [];
+ async function loadData() {
+ const { data } = await supabaseClient.from('test').select('*').limit(20);
+ loadedData = data;
+ }
-$: {
- if ($session.user && $session.user.id) {
+ $: if ($page.data.session.user) {
loadData();
}
-}
</script>
-{#if !$session.user}
- {#if $error}
- <p>{$error.message}</p>
- {/if}
- <h1>{$isLoading ? `Loading...` : `Loaded!`}</h1>
- <Auth
- supabaseClient={supabaseClient}
- providers={['google', 'github']}
- />
-{:else}
- <a href=="/api/auth/logout">Sign out</a>
- <p>user:</p>
- <pre>{JSON.stringify($session.user, null, 2)}</pre>
+{#if $page.data.session.user}
<p>client-side data fetching with RLS</p>
<pre>{JSON.stringify(loadedData, null, 2)}</pre>
{/if}
```
-### Server-side data fetching with RLS
-
-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 inject the request context into the supabase client:
+## Server-side data fetching with RLS
```html
-<!-- src/routes/profile.svelte -->
+<!-- src/routes/profile/+page.svelte -->
<script>
- export let user
- export let data
+ /** @type {import('./$types').PageData} */
+ export let data;
+ $: ({ user, tableData } = data);
</script>
<div>Protected content for {user.email}</div>
-<pre>{JSON.stringify(data, null, 2)}</pre>
+<pre>{JSON.stringify(tableData, null, 2)}</pre>
<pre>{JSON.stringify(user, null, 2)}</pre>
```
+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 `withAuth` helper to check if the user is authenticated. The helper extends the event with `session` and `getSupabaseClient()`:
+
```ts
-// src/routes/profile.ts
-import {
- supabaseServerClient,
- withApiAuth,
-} from '@supabase/auth-helpers-sveltekit'
-import type { RequestHandler } from './__types/profile'
+// src/routes/profile/+page.ts
+import type { PageLoad } from './$types';
+import { withAuth } from '@supabase/auth-helpers-sveltekit';
+import { redirect } from '@sveltejs/kit';
interface TestTable {
- id: string
- created_at: string
+ id: string;
+ created_at: string;
}
-interface GetOutput {
- user: User
- data: TestTable[]
+export const load: PageLoad = withAuth(async ({ getSupabaseClient, session }) => {
+ if (!session.user) {
+ throw redirect(303, '/');
+ }
+ const { data: tableData } = await getSupabaseClient()
+ .from<TestTable>('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
+// 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<GetOutput> = async ({ locals }) =>
- withApiAuth(
- {
- redirectTo: '/',
- user: locals.user,
- },
- async () => {
- const { data } = await supabaseServerClient(session.accessToken)
- .from<TestTable>('test')
- .select('*')
-
- return {
- body: {
- user: locals.user,
- data,
- },
+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 });
+);
+```
+
+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`.
+
+```ts
+// src/routes/posts/+page.server.ts
+import type { Actions } from './$types';
+import { withAuth } from '@supabase/auth-helpers-sveltekit';
+import { error, invalid } from '@sveltejs/kit';
+
+export const actions: Actions = {
+ createPost: withAuth(async ({ session, getSupabaseClient, request }) => {
+ if (!session.user) {
+ // the user is not signed in
+ 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 { error: createPostError, data: newPost } = await getSupabaseClient()
+ .from('posts')
+ .insert({ content });
+
+ if (createPostError) {
+ return invalid(500, {
+ supabaseErrorMessage: createPostError.message
+ });
+ }
+ return {
+ 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';
+
+export const actions: Actions = {
+ async signin({ request, cookies, url }) {
+ const formData = await request.formData();
+
+ 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`
+ }
+ );
+
+ if (error || !data) {
+ if (error?.status === 400) {
+ return invalid(400, {
+ error: 'Invalid credentials',
+ values: {
+ email
+ }
+ });
}
+ return invalid(500, {
+ error: 'Server error. Try again later.',
+ values: {
+ email
+ }
+ });
}
- )
+
+ saveSession(cookies, data);
+ throw redirect(303, '/dashboard');
+ }
+};
```
-## Protecting API routes
+Use `deleteSession` to delete the session cookies:
+
+```ts
+import type { Actions } from './$types';
+import { deleteSession } from '@supabase/auth-helpers-sveltekit/server';
+import { redirect } from '@sveltejs/kit';
+
+export const actions: Actions = {
+ async logout({ cookies }) {
+ deleteSession(cookies);
+ throw redirect(303, '/');
+ }
+};
+```
+
+## Custom session namespace
-Wrap an API Route to check that the user has a valid session. If they're not logged in the handler will return a
-303 and redirect header.
+If you wan´t to use something else than `locals.session` and `$page.data.session` you can do so by updating the types and creating three helper functions:
+```ts
+// src/app.d.ts
+declare namespace App {
+ interface Locals {
+ mySupabaseSession: import('@supabase/auth-helpers-sveltekit').SupabaseSession;
+ }
+ interface PageData {
+ mySupabaseSession: import('@supabase/auth-helpers-sveltekit').SupabaseSession;
+ }
+}
+
+// src/hooks.server.ts
+setupSupabaseServer({
+ supabaseClient,
+ cookieOptions: {
+ secure: !dev
+ },
+ // --- change location within locals ---
+ getSessionFromLocals: (locals) => locals.mySupabaseSession,
+ setSessionToLocals: (locals, session) => (locals.mySupabaseSession = session)
+});
+
+// src/lib/db.ts
+setupSupabaseClient({
+ supabaseClient,
+ // --- change location within pageData ---
+ getSessionFromPageData: (data) => data.mySupabaseSession
+});
+```
+
+## Migration from 0.6.11 and below to 0.7.0
+
+There are quite a lot of breaking changes in the latest 0.7.0 version of this library.
+
+### Environment variable prefix has changed
+
+0.6.11 and below: `VITE_`
+
+0.7.0: `PUBLIC_`
+
+e.g. `VITE_SUPABASE_URL` is now `PUBLIC_SUPABASE_URL`
+
+### Setup Supabase client
+
+0.6.11 and below:
+```js
+// src/lib/db.ts
+import { createSupabaseClient } from '@supabase/auth-helpers-sveltekit';
+
+const { supabaseClient } = createSupabaseClient(
+ import.meta.env.VITE_SUPABASE_URL as string,
+ import.meta.env.VITE_SUPABASE_ANON_KEY as string
+);
+
+export { supabaseClient };
+```
+
+0.7.0:
+```js
+// 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
+ }
+});
+```
+
+### Initialize client side code
+
+0.6.11 and below:
+```html
+<!-- src/routes/__layout.svelte -->
+<script>
+import { session } from '$app/stores';
+import { supabaseClient } from '$lib/db';
+import { SupaAuthHelper } from '@supabase/auth-helpers-svelte';
+</script>
+
+<SupaAuthHelper {supabaseClient} {session}>
+ <slot />
+</SupaAuthHelper>
+```
+
+0.7.0:
+```html
+<!-- src/routes/+layout.svelte -->
+<script lang="ts">
+ // we need to make sure the supabase instance is initialized on the client
+ import '$lib/db';
+ import { startSupabaseSessionSync } from '@supabase/auth-helpers-sveltekit';
+
+ // this sets up automatic token refreshing
+ startSupabaseSessionSync();
+</script>
+
+<slot />
+```
+
+> We no longer require the @supabase/auth-helpers-svelte library as the @supabase/auth-helpers-sveltekit library handles all the client side code too
+
+### Hooks setup
+
+0.6.11 and below:
+```ts
+// src/hooks.ts
+import { handleAuth } from '@supabase/auth-helpers-sveltekit';
+import type { GetSession, Handle } from '@sveltejs/kit';
+import { sequence } from '@sveltejs/kit/hooks';
+
+export const handle: Handle = sequence(...handleAuth());
+
+export const getSession: GetSession = async (event) => {
+ const { user, accessToken, error } = event.locals;
+ return {
+ user,
+ accessToken,
+ error
+ }
+}
+```
+
+0.7.0:
+```ts
+// src/hooks.server.ts
+// we need to 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
+// src/hooks.server.ts
+// we need to 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);
+```
+
+### Typings
+0.6.11 and below:
+```ts
+// src/app.d.ts
+/// <reference types="@sveltejs/kit" />
+// See https://kit.svelte.dev/docs/types#app
+// for information about these interfaces
+declare namespace App {
+ interface UserSession {
+ user: import('@supabase/supabase-js').User;
+ accessToken?: string;
+ }
+
+ interface Locals extends UserSession {
+ error: import('@supabase/supabase-js').ApiError;
+ }
+
+ interface Session extends UserSession {}
+
+ // interface Platform {}
+ // interface Stuff {}
+}
+```
+
+0.7.0:
+```ts
+// 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 PageData {
+ session: import('@supabase/auth-helpers-sveltekit').SupabaseSession;
+ }
+
+ // interface Error {}
+ // interface Platform {}
+}
+```
+
+### Checking user on the client
+
+0.6.11 and below:
+```html
+<!-- src/routes/index.svelte -->
+<script>
+ import { session } from '$app/stores';
+</script>
+
+{#if !$session.user}
+ <h1>I am not logged in</h1>
+{:else}
+ <h1>Welcome {$session.user.email}</h1>
+ <p>I am logged in!</p>
+{/if}
+```
+
+0.7.0:
+```html
+<!-- src/routes/+page.svelte -->
+<script>
+ import { page } from '$app/stores';
+</script>
+
+{#if !$page.data.session.user}
+ <h1>I am not logged in</h1>
+{:else}
+ <h1>Welcome {$page.data.session.user.email}</h1>
+ <p>I am logged in!</p>
+{/if}
+```
+
+### withPageAuth
+
+0.6.11 and below:
+```html
+<!-- // src/routes/protected-route.svelte -->
+<script lang="ts" context="module">
+import { supabaseServerClient, withPageAuth } from '@supabase/auth-helpers-sveltekit';
+import type { Load } from './__types/protected-page';
+
+export const load: Load = async ({ session }) =>
+withPageAuth(
+ {
+ redirectTo: '/',
+ user: session.user
+ },
+ async () => {
+ const { data } = await supabaseServerClient(session.accessToken).from('test').select('*');
+ return { props: { data, user: session.user } };
+ }
+);
+</script>
+
+<script>
+export let data;
+export let user;
+</script>
+
+<div>Protected content for {user.email}</div>
+<p>server-side fetched data with RLS:</p>
+<pre>{JSON.stringify(data, null, 2)}</pre>
+<p>user:</p>
+<pre>{JSON.stringify(user, null, 2)}</pre>
+```
+
+0.7.0:
+```html
+<!-- 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
+// 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 };
+});
+```
+
+### withApiAuth
+
+0.6.11 and below:
```ts
// src/routes/api/protected-route.ts
-import {
- supabaseServerClient,
- withApiAuth,
-} from '@supabase/auth-helpers-sveltekit'
-import type { RequestHandler } from './__types/protected-route'
+import { supabaseServerClient, withApiAuth } from "@supabase/auth-helpers-sveltekit";
+import type { RequestHandler } from "./__types/protected-route";
interface TestTable {
- id: string
- created_at: string
+ id: string;
+ created_at: string;
}
interface GetOutput {
- data: TestTable[]
+ data: TestTable[];
}
export const GET: RequestHandler<GetOutput> = async ({ locals, request }) =>
withApiAuth({ user: locals.user }, async () => {
// Run queries with RLS on the server
- const { data } = await supabaseServerClient(request)
- .from('test')
- .select('*')
+ const { data } = await supabaseServerClient(request).from("test").select("*");
return {
status: 200,
- body: { data },
- }
- })
+ body: { data }
+ };
+ });
```
-If you visit `/api/protected-route` without a valid session cookie, you will get a 303 response.
+
+0.7.0:
+```ts
+// 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 });
+);
+```
## Additional Links