diff --git a/docs/content/docs/framework-guides/sveltekit.mdx b/docs/content/docs/framework-guides/sveltekit.mdx index 05c84ca..63515b2 100644 --- a/docs/content/docs/framework-guides/sveltekit.mdx +++ b/docs/content/docs/framework-guides/sveltekit.mdx @@ -1,10 +1,10 @@ --- -title: Sveltekit -description: Install and configure Convex + Better Auth for Sveltekit. +title: SvelteKit +description: Install and configure Convex + Better Auth for SvelteKit. --- - Sveltekit support is currently community maintained, and relies on the + SvelteKit support is currently community maintained, and relies on the [@mmailaender/convex-better-auth-svelte](https://github.com/mmailaender/convex-better-auth-svelte) package. A complete working example is provided in the repo, and any issues can be reported there as well. @@ -353,12 +353,10 @@ You're now ready to start using Better Auth with Convex. ## Usage Check out the [Basic Usage](/basic-usage) guide for more information on general -usage. Below are usage notes specific to Sveltekit. +usage. Below are usage notes specific to SvelteKit. ### Using Better Auth from the client -Note: To add SSR support (`data.currentUser`) also add the `src/routes/+page.server.ts` file from the `Using Better Auth from the server` example. - ```svelte title="src/routes/+page.svelte" + + {@render children()} + ``` + + +
+ #### Prefetch user data + + For the best experience, also prefetch user data on the server to prevent content flash. + + ```ts title="src/routes/+layout.server.ts" + import type { LayoutServerLoad } from "./$types"; + import { api } from "$convex/_generated/api"; + import { createAuth } from "$convex/auth.js"; + import { createConvexHttpClient, getAuthState } from "@mmailaender/convex-better-auth-svelte/sveltekit"; + + export const load: LayoutServerLoad = async ({ locals, cookies }) => { + const authState = await getAuthState(createAuth, cookies); + + if (!authState.isAuthenticated) { + return { authState, currentUser: null }; + } + + const client = createConvexHttpClient({ token: locals.token }); + + try { + const currentUser = await client.query(api.auth.getCurrentUser, {}); + return { authState, currentUser }; + } catch { + return { authState, currentUser: null }; + } + }; + ``` + + Then use `initialData` in your queries to prevent data flash: + + ```ts title="src/routes/+page.svelte" + + ``` +
+ \ No newline at end of file