{task.text}
{/each} ``` -------------------------------- ### setupConvex(url, options?) Source: https://context7.com/axel-rock/convex-sveltekit/llms.txt Sets up the Convex client within the Svelte layout context. It reuses the singleton initialized by `initConvex` and makes it accessible to child components via `useConvexClient()`. It also registers a cleanup effect to close the WebSocket connection when the layout unmounts. ```APIDOC ## setupConvex(url, options?) ### Description Reuses the module-level singleton created by `initConvex` (or creates one on SSR paths), registers the client in Svelte context so child components can access it via `useConvexClient()`, and registers a cleanup effect to close the WebSocket when the layout unmounts. ### Method `setupConvex(url: string, options?: ConvexClientOptions)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```svelte {@render children()} ``` ### Response None (sets up context and cleanup) ### Error Handling None explicitly mentioned, relies on `initConvex`. ``` -------------------------------- ### initConvex(url, options?) Source: https://context7.com/axel-rock/convex-sveltekit/llms.txt Initializes the ConvexClient singleton at the module level. This function is idempotent and must be called before other Convex functions like `convexLoad` or `serverQuery` can be used. It ensures the client is available before SvelteKit's transport.decode runs. ```APIDOC ## initConvex(url, options?) ### Description Initializes the `ConvexClient` singleton at the module level (in `hooks.client.ts`), ensuring the client exists before SvelteKit's `transport.decode` runs and before any component hydrates. Idempotent — calling it multiple times is safe. Must be called before `convexLoad` or `serverQuery` can work. ### Method `initConvex(url: string, options?: ConvexClientOptions)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```ts // src/hooks.client.ts import { PUBLIC_CONVEX_URL } from "$env/static/public" import { initConvex } from "convex-sveltekit" // Runs before any component mounts or transport.decode fires initConvex(PUBLIC_CONVEX_URL) // With options (e.g. custom fetch, logger): // initConvex(PUBLIC_CONVEX_URL, { logger: console }) ``` ### Response None (initializes a singleton client) ### Error Handling Throws if `initConvex` has not been called when subsequent functions require it. ``` -------------------------------- ### Client Initialization Source: https://github.com/axel-rock/convex-sveltekit/blob/main/src/lib/README.md Functions for initializing the Convex client in your SvelteKit application. ```APIDOC ## initConvex(url) ### Description Initializes the Convex client early in the application lifecycle. This is typically done in `hooks.client.ts`. ### Method `initConvex` ### Parameters - **url** (string) - Required - The URL of the Convex deployment. ## setupConvex(url) ### Description Sets up the Convex client for use in SvelteKit, including context providers and cleanup logic. This is usually called in your root layout. ### Method `setupConvex` ### Parameters - **url** (string) - Required - The URL of the Convex deployment. ## setupConvexAuth(opts) ### Description Wires up authentication handling for the Convex client, enabling features like automatic user session management. ### Method `setupConvexAuth` ### Parameters - **opts** (object) - Required - Options for setting up authentication. Specific options are not detailed in the source. ## getConvexClient() ### Description Provides direct access to the raw Convex client instance. Use this as an escape hatch for advanced scenarios. ### Method `getConvexClient` ## useConvexClient() ### Description Retrieves the Convex client instance from the Svelte context. Useful for accessing the client within components. ### Method `useConvexClient` ``` -------------------------------- ### Create Better Auth Client with Convex Plugin Source: https://github.com/axel-rock/convex-sveltekit/blob/main/BETTER_AUTH.md Initializes the `better-auth` client with the `convexClient` plugin for seamless integration with Convex. ```typescript import { convexClient } from "@convex-dev/better-auth/client/plugins" import { createAuthClient } from "better-auth/svelte" export const authClient = createAuthClient({ plugins: [convexClient()], }) ``` -------------------------------- ### Initialize Convex and Authentication Hooks Source: https://github.com/axel-rock/convex-sveltekit/blob/main/BETTER_AUTH.md Sets up Convex client and sequences the `handleAuth` hook for server-side request handling. Requires `PUBLIC_CONVEX_URL` environment variable. ```typescript import { sequence } from "@sveltejs/kit/hooks" import { PUBLIC_CONVEX_URL } from "$env/static/public" import { initConvex } from "convex-sveltekit" import { handleAuth } from "$lib/auth.server.js" initConvex(PUBLIC_CONVEX_URL) export const handle = sequence(handleAuth) ``` -------------------------------- ### Set Environment Variables for Better Auth Source: https://github.com/axel-rock/convex-sveltekit/blob/main/BETTER_AUTH.md Configure essential environment variables for Better Auth, including the secret key and the SvelteKit origin URL. These are necessary for secure and correct operation. ```bash npx convex env set BETTER_AUTH_SECRET "$(openssl rand -base64 32)" npx convex env set BETTER_AUTH_URL "http://localhost:5173" # your SvelteKit origin ``` -------------------------------- ### Initialization Functions Source: https://github.com/axel-rock/convex-sveltekit/blob/main/README.md Functions for initializing Convex and its authentication layer within your SvelteKit application. ```APIDOC ## `initConvex(url, opts?, token?)` ### Description Initializes Convex on the client-side, typically used in `hooks.client.ts` for early setup. ### Parameters - **url** (string) - The Convex application URL. - **opts** (object, optional) - Additional options for initialization. - **token** (string, optional) - An initial authentication token. ``` ```APIDOC ## `setupConvex(url)` ### Description Sets up the Convex context and performs necessary cleanup, usually called in the root layout (`+layout.svelte`). ### Parameters - **url** (string) - The Convex application URL. ``` ```APIDOC ## `setupConvexAuth({ authClient, ... })` ### Description Bridges Better Auth with Convex, enabling seamless authentication flow between the two. ### Parameters - **authClient** (object) - The authentication client instance. - **other options** - Additional configuration for auth integration. ``` -------------------------------- ### Set up Convex Context in Root Layout Source: https://github.com/axel-rock/convex-sveltekit/blob/main/README.md Set up the Convex context in your root Svelte layout file. This makes Convex available throughout your application and handles cleanup. ```svelte ``` -------------------------------- ### Social Provider Configuration for Better Auth Source: https://github.com/axel-rock/convex-sveltekit/blob/main/BETTER_AUTH.md Configure social login providers by setting their credentials as Convex environment variables. Extend `createAuthOptions` with your provider details. ```typescript socialProviders: { github: { clientId: process.env.GITHUB_CLIENT_ID!, clientSecret: process.env.GITHUB_CLIENT_SECRET!, }, } ``` ```typescript await authClient.signIn.social({ provider: "github", callbackURL: "/" }) ``` -------------------------------- ### serverQuery(ref, args) / serverMutation(ref, args) / serverAction(ref, args) Source: https://context7.com/axel-rock/convex-sveltekit/llms.txt Enables one-shot Convex calls from server-side SvelteKit contexts (like load functions and form actions) using `ConvexHttpClient`. It automatically handles authentication via `event.locals.convexToken` and JWT refreshing, falling back to an unauthenticated call for public queries. ```APIDOC ## Server-Side Functions ### `serverQuery(ref, args)` / `serverMutation(ref, args)` / `serverAction(ref, args)` — Authenticated server-side calls One-shot Convex calls using `ConvexHttpClient`, for use in SvelteKit load functions and form actions. Automatically reads `event.locals.convexToken` from the current SvelteKit request context (via `getRequestEvent()`), refreshing the JWT if it expires within 60 seconds. Falls back to an unauthenticated singleton for public queries. ```ts // src/routes/profile/+page.server.ts import { serverQuery, serverMutation } from "convex-sveltekit" import { api } from "$convex/_generated/api" import { redirect } from "@sveltejs/kit" export const load = async () => { // Automatically authenticated via locals.convexToken const user = await serverQuery(api.auth.getCurrentUser, {}) if (!user) redirect(303, "/login") const tasks = await serverQuery(api.tasks.getForUser, { userId: user.id }) return { user, tasks } } export const actions = { createTask: async ({ request }) => { const data = await request.formData() const text = data.get("text") as string const id = await serverMutation(api.tasks.create, { text }) return { id } }, } ``` ``` -------------------------------- ### Convex SvelteKit Auth Helpers Source: https://github.com/axel-rock/convex-sveltekit/blob/main/BETTER_AUTH.md Utility functions for integrating Better Auth with Convex SvelteKit. ```APIDOC ## Convex SvelteKit Auth Helpers ### Description Provides helper functions to integrate Better Auth sessions with ConvexClient and manage user state. | `convex-sveltekit` function | Purpose | | --- | --- | | `setupConvexAuth({ authClient, initialToken })` | Wire Better Auth sessions into ConvexClient | | `useConvexAuth()` | Read `{ isAuthenticated, isLoading }` | | `convexUser(data)` | SSR-to-live user transport (seeds from JWT, upgrades to Convex subscription) | | `encodeConvexUser` / `decodeConvexUser` | Transport hooks for `ConvexUserResult` | | `serverQuery` / `serverMutation` / `serverAction` | Auto-authenticated via `locals.convexToken` | ``` -------------------------------- ### Convex Live Queries with convexQuery Source: https://github.com/axel-rock/convex-sveltekit/blob/main/README.md Demonstrates how to use convexQuery in a Svelte component for real-time data fetching and display. Supports conditional queries by returning 'skip'. ```svelte {#if tasks.isLoading}Loading...
{:else} {#each tasks.data ?? [] as task}{task.text}
{/each} {/if} ``` ```typescript const user = convexQuery(api.users.get, () => (userId ? { id: userId } : "skip")) ``` -------------------------------- ### Email/Password Authentication Source: https://github.com/axel-rock/convex-sveltekit/blob/main/BETTER_AUTH.md Handles user sign-up, sign-in, and sign-out using email and password. ```APIDOC ## Email/Password Authentication ### Description Provides methods for user authentication via email and password. ### Methods - **Sign Up** - `authClient.signUp.email({ name, email, password })` - **Sign In** - `authClient.signIn.email({ email, password })` - **Sign Out** - `authClient.signOut()` ### Usage ```ts import { authClient } from "$lib/auth-client.js" // Sign up await authClient.signUp.email({ name, email, password }) // Sign in await authClient.signIn.email({ email, password }) // Sign out await authClient.signOut() ``` ``` -------------------------------- ### Live Queries with convexQuery Source: https://github.com/axel-rock/convex-sveltekit/blob/main/src/lib/README.md Provides component-level live queries that automatically update data via WebSocket. Supports conditional queries by returning 'skip' when data is not needed. ```svelte {#if tasks.isLoading}Loading...
{:else} {#each tasks.data ?? [] as task}{task.text}
{/each} {/if} ``` ```typescript const user = convexQuery(api.users.get, () => (userId ? { id: userId } : "skip")) ``` -------------------------------- ### Define App Locals and User Types Source: https://github.com/axel-rock/convex-sveltekit/blob/main/BETTER_AUTH.md Extends the SvelteKit `App.Locals` interface to include `convexToken` and `user` properties for server-side data. ```typescript declare global { namespace App { interface Locals { convexToken?: string user?: { id: string email: string name: string image?: string | null } } } } export {} ``` -------------------------------- ### Configure Auth Providers for Better Auth Source: https://github.com/axel-rock/convex-sveltekit/blob/main/BETTER_AUTH.md Set up the authentication configuration provider for Better Auth. This file defines how authentication is handled within your Convex application. ```typescript import { getAuthConfigProvider } from "@convex-dev/better-auth/auth-config" import type { AuthConfig } from "convex/server" export default { providers: [getAuthConfigProvider()], } satisfies AuthConfig ``` -------------------------------- ### Seed User from JWT in SvelteKit Server Load Source: https://github.com/axel-rock/convex-sveltekit/blob/main/README.md Load user data on the server and pass it to the client. This ensures the user is available on initial render and seamlessly transitions to live data. ```typescript // +layout.server.ts — seeds user from JWT, auto-upgrades to live Convex data export const load = async ({ locals }) => ({ user: convexUser(locals.user), convexToken: locals.convexToken ?? null, }) ``` -------------------------------- ### Mutating Data: Before and After Source: https://github.com/axel-rock/convex-sveltekit/blob/main/README.md Illustrates the shift from manual Convex client mutation calls to using the streamlined convexForm for SvelteKit forms. ```diff - const client = useConvexClient() - let text = $state("") - let pending = $state(false) - async function submit() { - pending = true - await client.mutation(api.tasks.create, { text }) - text = ""; pending = false - } + const form = convexForm(z.object({ text: z.string() }), api.tasks.create) + + ``` -------------------------------- ### Programmatic Mutations and Actions with convexCommand Source: https://github.com/axel-rock/convex-sveltekit/blob/main/README.md Demonstrates the use of convexCommand for direct programmatic calls to Convex mutations or actions, bypassing form-based submission. ```typescript const removeTask = convexCommand(api.tasks.remove) await removeTask({ id: task._id }) const generate = convexCommand(api.ai.generate, "action") await generate({ prompt: "..." }) ``` -------------------------------- ### Client Access Source: https://github.com/axel-rock/convex-sveltekit/blob/main/README.md Functions for accessing the raw Convex client instance. ```APIDOC ## `getConvexClient()` ### Description Provides direct access to the raw Convex client instance, serving as an escape hatch for advanced use cases. ### Returns The raw Convex client instance. ``` ```APIDOC ## `useConvexClient()` ### Description Retrieves the Convex client instance from the Svelte context. ### Returns The Convex client instance available in the Svelte context. ``` -------------------------------- ### Initialize Convex Client in Server Hooks Source: https://github.com/axel-rock/convex-sveltekit/blob/main/README.md Initialize the Convex client in server hooks if you are using `convexLoad()` or `serverQuery()` in your load functions. This ensures server-side data fetching works. ```typescript // src/hooks.server.ts import { initConvex } from "convex-sveltekit" import { PUBLIC_CONVEX_URL } from "$env/static/public" initConvex(PUBLIC_CONVEX_URL) ``` -------------------------------- ### useConvexClient() Source: https://context7.com/axel-rock/convex-sveltekit/llms.txt A hook for accessing the `ConvexClient` instance from within Svelte components. It reads the client from the Svelte context, which must have been previously set up by `setupConvex()` in a parent layout. ```APIDOC ## useConvexClient() ### Description Reads the `ConvexClient` from Svelte context. Must be called inside a component tree that has `setupConvex()` in a parent layout. ### Method `useConvexClient(): ConvexClient` ### Parameters None ### Request Example ```svelte ``` ### Response - **ConvexClient**: The Convex client instance available in the Svelte context. ### Error Handling Throws if called outside a context where `setupConvex()` has been invoked. ``` -------------------------------- ### Environment Variables for Convex URLs Source: https://github.com/axel-rock/convex-sveltekit/blob/main/BETTER_AUTH.md Specifies the necessary environment variables for Convex deployment URL and site URL. ```dotenv PUBLIC_CONVEX_URL=https://your-deployment.convex.cloud PUBLIC_CONVEX_SITE_URL=https://your-deployment.convex.site ``` -------------------------------- ### Read Authentication State with useConvexAuth Source: https://context7.com/axel-rock/convex-sveltekit/llms.txt Provides authentication state (`isAuthenticated`, `isLoading`) from Svelte context. Must be called within a component tree that has `setupConvexAuth()` in a parent. Skips queries until authenticated. ```svelte {#if auth.isLoading}Checking auth...
{:else if auth.isAuthenticated}Welcome, {profile.data?.name}
{:else} Sign in {/if} ``` -------------------------------- ### Proxy API Requests to Convex Source: https://github.com/axel-rock/convex-sveltekit/blob/main/BETTER_AUTH.md Proxies requests from `/api/auth/*` to your Convex site URL. Ensures cookies are correctly set on your SvelteKit domain. Requires `PUBLIC_CONVEX_SITE_URL` environment variable. ```typescript import { PUBLIC_CONVEX_SITE_URL } from "$env/static/public" import type { RequestHandler } from "./$types" const proxy: RequestHandler = async ({ request }) => { const url = new URL(request.url) const target = `${PUBLIC_CONVEX_SITE_URL}${url.pathname}${url.search}` const proxyRequest = new Request(target, { method: request.method, headers: request.headers, body: request.body, // @ts-expect-error needed for streaming request bodies duplex: "half", }) proxyRequest.headers.set("accept-encoding", "application/json") return fetch(proxyRequest, { redirect: "manual" }) } export const GET = proxy export const POST = proxy ``` -------------------------------- ### convexCommand(ref, type?) Source: https://context7.com/axel-rock/convex-sveltekit/llms.txt Creates a callable command for programmatic mutations and actions. It returns a `Promise` with an `.updates()` method for releasing optimistic overrides. Specify `"action"` for Convex actions running in the Node.js runtime. ```APIDOC ## Commands ### `convexCommand(ref, type?)` — Programmatic mutations and actions Creates a callable command wrapping a Convex mutation or action. Returns a `Promise` with an `.updates()` chainable for releasing optimistic overrides after completion. Pass `"action"` as the second argument for Convex actions running in the Node.js runtime. ```svelte {#each tasks.data ?? [] as task (task._id)} {/each} ``` ``` -------------------------------- ### Authentication Source: https://github.com/axel-rock/convex-sveltekit/blob/main/src/lib/README.md Utilities for managing user authentication state and sessions. ```APIDOC ## useConvexAuth() ### Description Provides access to the authentication state within Svelte components, including properties like `isAuthenticated`. ### Method `useConvexAuth` ## convexUser(data) ### Description Manages user sessions, enabling an upgrade from SSR-provided data to a live-updating user session. ### Method `convexUser` ### Parameters - **data** (object) - Required - Data related to the user session, likely including authentication tokens or user information. ``` -------------------------------- ### Client-side reactive user session Source: https://github.com/axel-rock/convex-sveltekit/blob/main/src/lib/README.md Uses the user data loaded on the server and makes it reactive on the client. Profile images are preloaded to prevent visual flicker. ```svelte{task.text}
{/each} ``` -------------------------------- ### convexLoad Source: https://context7.com/axel-rock/convex-sveltekit/llms.txt Fetches Convex data server-side via ConvexHttpClient (auth-aware), wraps it in a ConvexLoadResult for transport, and on the client decodes it into a live WebSocket subscription. On client-side navigation it creates a live subscription directly. ```APIDOC ### `convexLoad(ref, args)` — SSR query in load functions with live upgrade Fetches Convex data server-side via `ConvexHttpClient` (auth-aware), wraps it in a `ConvexLoadResult` for transport, and on the client decodes it into a live WebSocket subscription. On client-side navigation it creates a live subscription directly. The result is a `ConvexQueryResult` — same shape as `convexQuery`. ```ts // src/routes/+page.ts import { convexLoad } from "convex-sveltekit" import { api } from "$convex/_generated/api" export const load = async () => ({ // Server: fetches via HTTP, wraps for transport // Client: creates live subscription with initial data tasks: await convexLoad(api.tasks.get, {}), }) ``` ```svelte {#each tasks.data ?? [] as task (task._id)}{task.text}
{/each}Loading: {tasks.isLoading} | Items: {tasks.data?.length ?? 0}
``` ``` -------------------------------- ### Configure Convex Transport Hooks Source: https://context7.com/axel-rock/convex-sveltekit/llms.txt Sets up transport hooks for encoding and decoding ConvexLoadResult and ConvexUserResult. Required for `convexLoad()` and `convexUser()` in SvelteKit load functions. ```typescript import { encodeConvexLoad, decodeConvexLoad, encodeConvexUser, decodeConvexUser, } from "convex-sveltekit" import { api } from "$convex/_generated/api" export const transport = { // Required for convexLoad() in load functions ConvexLoadResult: { encode: (value: unknown) => encodeConvexLoad(value), decode: (encoded: { refName: string; args: Record{task.text}
{/each}Loading: {tasks.isLoading} | Items: {tasks.data?.length ?? 0}
``` -------------------------------- ### Register HTTP Routes for Better Auth Source: https://github.com/axel-rock/convex-sveltekit/blob/main/BETTER_AUTH.md Set up the HTTP router in Convex to handle Better Auth routes. This involves registering the authentication component's routes with the HTTP router. ```typescript import { httpRouter } from "convex/server" import { authComponent, createAuth } from "./auth" const http = httpRouter() authComponent.registerRoutes(http, createAuth) export default http ``` -------------------------------- ### Mutation and Form Handling Source: https://github.com/axel-rock/convex-sveltekit/blob/main/README.md Functions for performing mutations, handling forms, and executing server-side actions. ```APIDOC ## `convexForm(schema, mutationRef)` ### Description Provides a convenient way to handle form submissions with SvelteKit's developer experience, integrating with Convex mutations. ### Parameters - **schema** (object) - A validation schema (e.g., Zod schema) for the form data. - **mutationRef** (object) - A reference to the Convex mutation function. ``` ```APIDOC ## `convexCommand(ref, type?)` ### Description Allows programmatic execution of mutations or actions in Convex. ### Parameters - **ref** (object) - A reference to the Convex mutation or action function. - **type** (string, optional) - Specifies the type of command (e.g., 'mutation', 'action'). ``` ```APIDOC ## `serverMutation(ref, args)` ### Description Executes a one-shot server-side mutation. ### Parameters - **ref** (object) - A reference to the Convex mutation function. - **args** (object) - Arguments for the mutation. ``` ```APIDOC ## `serverAction(ref, args)` ### Description Executes a one-shot server-side action. ### Parameters - **ref** (object) - A reference to the Convex action function. - **args** (object) - Arguments for the action. ``` -------------------------------- ### convexForm Source: https://context7.com/axel-rock/convex-sveltekit/llms.txt Provides SvelteKit form developer experience over Convex mutations, including validation, pending state, and error display. ```APIDOC ## Forms ### `convexForm(schema, mutationRef, mapArgs?)` — SvelteKit form DX over Convex mutations Creates a form object that spreads onto ` {#if createTask.result}Created task ID: {createTask.result}
{/if} ``` ```