### Install Convex Auth Svelte
Source: https://context7.com/mmailaender/convex-auth-svelte/llms.txt
Install the package and its required peer dependencies using npm or pnpm. Run the Convex Auth initializer and add authTables to your Convex schema.
```bash
# npm
npm install @mmailaender/convex-auth-svelte @convex-dev/auth @auth/core convex convex-svelte
# pnpm
pnpm add @mmailaender/convex-auth-svelte @convex-dev/auth @auth/core convex convex-svelte
```
```bash
npx @convex-dev/auth
```
```typescript
// convex/schema.ts
import { defineSchema } from "convex/server";
import { authTables } from "@convex-dev/auth/server";
const schema = defineSchema({
...authTables,
messages: defineTable({ body: v.string(), authorId: v.id("users") }),
});
export default schema;
```
--------------------------------
### Install Dependencies for Convex Auth Svelte
Source: https://github.com/mmailaender/convex-auth-svelte/blob/main/src/lib/svelte/README.md
Install the necessary packages for Convex Auth Svelte using npm, pnpm, or yarn.
```bash
# npm
npm install @mmailaender/convex-auth-svelte @convex-dev/auth @auth/core convex convex-svelte
# pnpm
pnpm add @mmailaender/convex-auth-svelte @convex-dev/auth @auth/core convex convex-svelte
# yarn
yarn add @mmailaender/convex-auth-svelte @convex-dev/auth @auth/core convex convex-svelte
```
--------------------------------
### Install Dependencies for Convex Auth
Source: https://github.com/mmailaender/convex-auth-svelte/blob/main/src/lib/sveltekit/README.md
Install the necessary packages for Convex authentication in your SvelteKit project using npm, pnpm, or yarn.
```bash
npm install @convex-dev/auth @auth/core @mmailaender/convex-auth-svelte
# or
pnpm add @convex-dev/auth @auth/core @mmailaender/convex-auth-svelte
# or
yarn add @convex-dev/auth @auth/core @mmailaender/convex-auth-svelte
```
--------------------------------
### Run E2E Tests with Local Convex Backend
Source: https://github.com/mmailaender/convex-auth-svelte/blob/main/e2e/README.md
Execute end-to-end tests by specifying the path to a locally built Convex backend. Ensure you have completed the initial setup for the Convex backend.
```bash
CONVEX_LOCAL_BACKEND_PATH=/path/to/your/convex-backend npm run test
```
--------------------------------
### Setup Convex Auth Client (Svelte / client-only)
Source: https://context7.com/mmailaender/convex-auth-svelte/llms.txt
Initializes the Convex Auth client for a plain Svelte 5 application. Call it once in your root component. It creates a ConvexClient, registers an auth token provider, and stores tokens in localStorage by default.
```svelte
```
--------------------------------
### Initialize Test User for Convex Auth
Source: https://github.com/mmailaender/convex-auth-svelte/blob/main/e2e/README.md
Create a test user for end-to-end authentication testing using the Convex CLI. This command is part of the manual setup process.
```bash
npx convex run tests:init
```
--------------------------------
### Setup Convex Auth in SvelteKit Layout
Source: https://context7.com/mmailaender/convex-auth-svelte/llms.txt
Initialize Convex auth in your root SvelteKit layout for SSR awareness. Ensure `getServerState` is correctly configured to read auth state from server data.
```svelte
{@render children()}
```
```typescript
// src/routes/+layout.server.ts
import { createConvexAuthHandlers } from '@mmailaender/convex-auth-svelte/sveltekit/server';
import type { LayoutServerLoad } from './$types';
const { getAuthState } = createConvexAuthHandlers();
export const load: LayoutServerLoad = async (event) => {
return { authState: await getAuthState(event) };
};
```
--------------------------------
### Authenticated Convex Queries and Mutations in Svelte
Source: https://context7.com/mmailaender/convex-auth-svelte/llms.txt
Use `useQuery` and `useConvexClient` from `convex-svelte` to make reactive queries and mutations that automatically carry the user's JWT. This example shows how to fetch viewer data, messages, and send new messages.
```svelte
{#if viewer.data}
Welcome, {viewer.data.name}!
{/if}
{#each messages.data ?? [] as msg}
{msg.body}
{/each}
```
--------------------------------
### Access Raw Token with useAuth in Svelte
Source: https://github.com/mmailaender/convex-auth-svelte/blob/main/src/lib/svelte/README.md
Retrieve the raw authentication token using `auth.token` or by calling `auth.fetchAccessToken()` when needed, for example, to attach it to custom requests.
```svelte
```
--------------------------------
### Initialize Backend Authentication with Convex CLI
Source: https://github.com/mmailaender/convex-auth-svelte/blob/main/src/lib/svelte/README.md
Run the Convex CLI command to set up your project for authentication.
```bash
npx @convex-dev/auth
```
--------------------------------
### setupConvexAuth
Source: https://github.com/mmailaender/convex-auth-svelte/blob/main/src/lib/svelte/README.md
Initializes authentication for Convex. It creates or uses a ConvexClient, registers an auth provider, and configures token storage.
```APIDOC
## setupConvexAuth(options)
### Description
Initializes authentication for Convex.
### Parameters
#### Options
- **client** (ConvexClient) - Optional - The Convex client instance to use.
- **convexUrl** (string) - Required - The URL of the Convex deployment.
- **storage** (TokenStorage | null) - Optional - The storage mechanism for tokens (defaults to `localStorage`).
- **storageNamespace** (string) - Optional - The namespace for token storage.
- **replaceURL** ((relativeUrl: string) => void | Promise) - Optional - A function to handle URL replacement.
- **options** (ConvexClientOptions) - Optional - Additional options for the Convex client.
### Behavior
- Creates or uses an existing `ConvexClient`.
- Registers an authentication provider that supplies access tokens to the client.
- Stores tokens using the specified `TokenStorage`.
### Returns
- The auth client instance used internally.
```
--------------------------------
### setupConvexAuth Function
Source: https://context7.com/mmailaender/convex-auth-svelte/llms.txt
Initializes Convex Auth in SvelteKit layouts, enabling SSR awareness by reading server-supplied tokens and handling sign-in/out requests through a local API route.
```APIDOC
## `setupConvexAuth` (SvelteKit / SSR-aware)
Initializes auth in the root SvelteKit layout. This version reads server-supplied tokens via `getServerState` for authenticated SSR renders, proxies sign-in/out calls through the local `/api/auth` route, and stores the refresh token in server-side cookies.
### Parameters
- **`options`** (object) - Configuration options.
- **`getServerState`** (function) - A function that returns the server-provided auth state. Typically `() => data.authState`.
- **`convexUrl`** (string, optional) - The Convex deployment URL. Defaults to `process.env.PUBLIC_CONVEX_URL`.
- **`storage`** (string, optional) - Storage type, e.g., 'inMemory'. Defaults to using localStorage.
- **`apiRoute`** (string, optional) - The local API route for auth proxying. Defaults to '/api/auth'.
### Example Usage
```svelte
{@render children()}
```
```ts
// src/routes/+layout.server.ts
import { createConvexAuthHandlers } from '@mmailaender/convex-auth-svelte/sveltekit/server';
import type { LayoutServerLoad } from './$types';
const { getAuthState } = createConvexAuthHandlers();
export const load: LayoutServerLoad = async (event) => {
return { authState: await getAuthState(event) };
};
```
```
--------------------------------
### Create Server-Side Auth Handlers
Source: https://context7.com/mmailaender/convex-auth-svelte/llms.txt
Factory for server-side helpers in SvelteKit. Use `isAuthenticated` to guard routes and `createConvexHttpClient` to make authenticated Convex queries from server-side code.
```typescript
// src/routes/dashboard/+page.server.ts
import { createConvexAuthHandlers } from '@mmailaender/convex-auth-svelte/sveltekit/server';
import { redirect } from '@sveltejs/kit';
import { api } from '$convex/_generated/api.js';
import type { PageServerLoad } from './$types';
const { isAuthenticated, createConvexHttpClient } =
createConvexAuthHandlers({ convexUrl: process.env.CONVEX_URL });
export const load: PageServerLoad = async (event) => {
// Guard: redirect unauthenticated users
if (!(await isAuthenticated(event))) {
throw redirect(302, `/signin?redirectTo=${encodeURIComponent(event.url.pathname)}`);
}
// Authenticated server-side Convex query
const client = await createConvexHttpClient(event);
const viewer = await client.query(api.users.viewer, {});
return { viewer };
};
```
--------------------------------
### Load Auth State in SvelteKit Layout Server
Source: https://github.com/mmailaender/convex-auth-svelte/blob/main/src/lib/sveltekit/README.md
Create a layout server load function to fetch and provide the authentication state to the client-side layout component.
```typescript
// src/routes/+layout.server.ts
import { createConvexAuthHandlers } from '@mmailaender/convex-auth-svelte/sveltekit/server';
import type { LayoutServerLoad } from './$types';
// Create auth handlers - convexUrl is automatically detected from environment
const { getAuthState } = createConvexAuthHandlers();
// Export load function to provide auth state to layout
export const load: LayoutServerLoad = async (event) => {
return { authState: await getAuthState(event) };
};
```
--------------------------------
### SvelteKit Email/Password Authentication
Source: https://github.com/mmailaender/convex-auth-svelte/blob/main/src/lib/sveltekit/README.md
Handles user sign-up and sign-in using email and password with Convex Auth SvelteKit. Requires email and password credentials and specifies the authentication flow.
```html
```
--------------------------------
### Initialize Convex Auth Client-Side
Source: https://github.com/mmailaender/convex-auth-svelte/blob/main/src/lib/svelte/README.md
Call `setupConvexAuth` in your root Svelte component, providing either a `convexUrl` or a `ConvexClient` instance. This is for client-only Svelte apps.
```svelte
```
--------------------------------
### Initialize Convex Auth in SvelteKit Layout
Source: https://github.com/mmailaender/convex-auth-svelte/blob/main/src/lib/sveltekit/README.md
Set up Convex authentication in your root SvelteKit layout component by calling `setupConvexAuth` with the server-side auth state.
```svelte
{@render children()}
```
--------------------------------
### Configure Server-side Auth Hooks in SvelteKit
Source: https://github.com/mmailaender/convex-auth-svelte/blob/main/src/lib/sveltekit/README.md
Set up authentication hooks in `hooks.server.ts` to automatically handle authentication for POST requests to `/api/auth`.
```typescript
// src/hooks.server.ts
import { sequence } from '@sveltejs/kit/hooks';
import { createConvexAuthHooks } from '@mmailaender/convex-auth-svelte/sveltekit/server';
// Create auth hooks - convexUrl is automatically detected from environment
const { handleAuth } = createConvexAuthHooks();
// Apply hooks in sequence
export const handle = sequence(
handleAuth, // This handles all POST requests to /api/auth automatically
// Your other custom handlers...
);
```
--------------------------------
### SvelteKit User Login/Logout Component
Source: https://github.com/mmailaender/convex-auth-svelte/blob/main/src/lib/sveltekit/README.md
Implement a basic login and logout component using `useAuth` from Convex Auth SvelteKit. Handles loading states, authenticated views, and sign-in with Google.
```html
{#if isLoading}
Loading authentication state...
{:else if isAuthenticated}
Welcome, authenticated user!
{:else}
Please sign in
{/if}
```
--------------------------------
### Implement Custom Token Storage
Source: https://context7.com/mmailaender/convex-auth-svelte/llms.txt
Implement the `TokenStorage` interface to integrate custom key-value stores for token management, such as `sessionStorage` or secure mobile storage. This allows for alternatives to the default `localStorage`.
```typescript
// custom-storage.ts
import { setupConvexAuth, type TokenStorage } from '@mmailaender/convex-auth-svelte/svelte';
// Example: sessionStorage (per-tab isolation)
const sessionTokenStorage: TokenStorage = {
getItem: (key) => sessionStorage.getItem(key),
setItem: (key, value) => sessionStorage.setItem(key, value),
removeItem: (key) => sessionStorage.removeItem(key),
};
// Example: async encrypted store (e.g. React Native SecureStore)
const secureStorage: TokenStorage = {
getItem: async (key) => await SecureStore.getItemAsync(key) ?? null,
setItem: async (key, value) => { await SecureStore.setItemAsync(key, value); },
removeItem: async (key) => { await SecureStore.deleteItemAsync(key); },
};
// Use in App.svelte
setupConvexAuth({
convexUrl: import.meta.env.VITE_CONVEX_URL,
storage: sessionTokenStorage,
storageNamespace: 'my-app-v2', // avoids key collisions between deployments
});
```
--------------------------------
### SvelteKit Server-side Authenticated Requests
Source: https://github.com/mmailaender/convex-auth-svelte/blob/main/src/lib/sveltekit/README.md
Create an authenticated Convex HTTP client on the server-side within SvelteKit using `createConvexHttpClient`. This client automatically includes authentication tokens if the user is signed in.
```typescript
// src/routes/some-page/+page.server.ts
import type { PageServerLoad } from './$types';
import { api } from '$convex/_generated/api.js';
import { createConvexAuthHandlers } from '@mmailaender/convex-auth-svelte/sveltekit/server';
export const load = (async (event) => {
const { createConvexHttpClient } = createConvexAuthHandlers();
// Create an authenticated HTTP client
// If the user is authenticated, this client will have the auth token
// If not, it will be an unauthenticated client
const client = await createConvexHttpClient(event);
// Make authenticated queries to your Convex backend
const viewer = await client.query(api.users.viewer, {});
return { viewer };
}) satisfies PageServerLoad;
```
--------------------------------
### SvelteKit Auth State Checking
Source: https://github.com/mmailaender/convex-auth-svelte/blob/main/src/lib/sveltekit/README.md
Conditionally render UI elements based on the user's authentication status using `useAuth` from Convex Auth SvelteKit. Checks for loading, authenticated, and unauthenticated states.
```html
{#if isLoading}
Loading...
{:else if isAuthenticated}
You are signed in!
{:else}
Not signed in.
{/if}
```
--------------------------------
### Use useAuth hook in Svelte/SvelteKit
Source: https://context7.com/mmailaender/convex-auth-svelte/llms.txt
Access reactive auth state (loading, authenticated, token) and perform auth actions like sign-in, sign-out, and fetching tokens. Wrap reactive getters in `$derived` to track changes.
```svelte
{#if isLoading}
Loading…
{:else if isAuthenticated}
Signed in • token present: {!!token}
{:else}
{/if}
```
--------------------------------
### createConvexAuthHandlers Factory
Source: https://context7.com/mmailaender/convex-auth-svelte/llms.txt
A factory function for creating server-side authentication helpers used in SvelteKit server route files.
```APIDOC
## `createConvexAuthHandlers`
Factory for server-side helpers used in `+layout.server.ts` and `+page.server.ts` files. Accepts an optional `convexUrl`.
### Returns
An object containing:
- **`getAuthState(event)`**: Retrieves the authentication state from the request event.
- **`isAuthenticated(event)`**: Returns a boolean indicating if the user is authenticated.
- **`createConvexHttpClient(event)`**: Creates a Convex HTTP client instance, authenticated for server-side requests.
### Example Usage
```ts
// src/routes/dashboard/+page.server.ts
import { createConvexAuthHandlers } from '@mmailaender/convex-auth-svelte/sveltekit/server';
import { redirect } from '@sveltejs/kit';
import { api } from '$convex/_generated/api.js';
import type { PageServerLoad } from './$types';
const { isAuthenticated, createConvexHttpClient } = createConvexAuthHandlers();
export const load: PageServerLoad = async (event) => {
if (!(await isAuthenticated(event))) {
throw redirect(302, `/signin?redirectTo=${encodeURIComponent(event.url.pathname)}`);
}
const client = await createConvexHttpClient(event);
const viewer = await client.query(api.users.viewer, {});
return { viewer };
};
```
```
--------------------------------
### useAuth Hook
Source: https://context7.com/mmailaender/convex-auth-svelte/llms.txt
The `useAuth` hook provides reactive authentication state (isLoading, isAuthenticated, token) and methods for sign-in, sign-out, and fetching JWTs within Svelte and SvelteKit applications.
```APIDOC
## `useAuth` (Svelte & SvelteKit)
Returns a reactive auth object from Svelte context. Works in both `svelte` and `sveltekit` entry points after `setupConvexAuth` has been called. The returned properties (`isLoading`, `isAuthenticated`, `token`) are Svelte 5 reactive getters — wrap them in `$derived` to track changes.
### Methods
- **`signIn(provider, options?)`**: Initiates the sign-in process. `provider` can be 'google', 'password', or 'resend-otp'. `options` vary by provider (e.g., `{ email, password, flow: 'signUp' | 'signIn' }` for 'password').
- **`signOut()`**: Signs the user out.
- **`fetchAccessToken()`**: Retrieves the raw JWT.
### Example Usage
```svelte
{#if isLoading}
Loading…
{:else if isAuthenticated}
Signed in • token present: {!!token}
{:else}
{/if}
```
```
--------------------------------
### App-wide Auth: Whitelist Pattern (Auth-first)
Source: https://github.com/mmailaender/convex-auth-svelte/blob/main/src/lib/sveltekit/README.md
Implement app-wide authentication by defining public routes and redirecting unauthenticated users to signin. This hook-based approach ensures all routes, except those explicitly whitelisted, require authentication.
```typescript
// src/hooks.server.ts
import { sequence } from '@sveltejs/kit/hooks';
import { redirect, type Handle } from '@sveltejs/kit';
import {
createConvexAuthHooks,
createRouteMatcher
} from '@mmailaender/convex-auth-svelte/sveltekit/server';
const isPublicRoute = createRouteMatcher([
'/signin',
'/register',
'/about',
// Note: No need to add '/api/auth' here as the handleAuth middleware
// will process those requests before this middleware runs
]);
// Create auth hooks
const { handleAuth, isAuthenticated } = createConvexAuthHooks();
// Create custom auth handler
const requireAuth: Handle = async ({ event, resolve }) => {
// Allow public routes
if (isPublicRoute(event.url.pathname)) {
return resolve(event);
}
// Check if user is authenticated
if (!(await isAuthenticated(event))) {
// Redirect to signin if not authenticated
throw redirect(302, `/signin?redirectTo=${encodeURIComponent(event.url.pathname + event.url.search)}`);
}
// User is authenticated, proceed
return resolve(event);
};
// Apply hooks in sequence
export const handle = sequence(
handleAuth, // This MUST come first to handle auth requests
requireAuth // Then enforce authentication
);
```
--------------------------------
### Create Convex Auth Hooks for SvelteKit
Source: https://context7.com/mmailaender/convex-auth-svelte/llms.txt
Use `createConvexAuthHooks` in `hooks.server.ts` to manage authentication middleware. It intercepts auth requests, proxies Convex actions, and handles JWT/refresh tokens. Ensure `handleAuth` precedes other handlers like `requireAuth` in the SvelteKit `sequence`.
```typescript
// src/hooks.server.ts
import { sequence } from '@sveltejs/kit/hooks';
import { redirect, type Handle } from '@sveltejs/kit';
import {
createConvexAuthHooks,
createRouteMatcher,
} from '@mmailaender/convex-auth-svelte/sveltekit/server';
// Protect all routes except public ones
const isPublicRoute = createRouteMatcher(['/signin', '/signup', '/about']);
const { handleAuth, isAuthenticated } = createConvexAuthHooks({
convexUrl: process.env.CONVEX_URL,
apiRoute: '/api/auth', // default
verbose: false, // set true for debug logs
cookieConfig: {
path: '/',
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax',
// maxAge: 60 * 60 * 24 * 7, // optional: override 1-hour JWT / 30-day refresh defaults
},
});
const requireAuth: Handle = async ({ event, resolve }) => {
if (!isPublicRoute(event.url.pathname) && !(await isAuthenticated(event))) {
throw redirect(302, `/signin?redirectTo=${encodeURIComponent(event.url.pathname + event.url.search)}`);
}
return resolve(event);
};
// handleAuth MUST come before requireAuth
export const handle = sequence(handleAuth, requireAuth);
```
--------------------------------
### useAuth
Source: https://github.com/mmailaender/convex-auth-svelte/blob/main/src/lib/svelte/README.md
Provides a unified authentication object with state and methods for managing user authentication.
```APIDOC
## useAuth()
### Description
Returns a unified authentication object that provides the current authentication state and methods to interact with the authentication system.
### Returns
An object with the following properties:
- **isLoading** (boolean) - Indicates if the authentication state is currently being loaded.
- **isAuthenticated** (boolean) - Indicates if the user is currently authenticated.
- **token** (string | null) - The current authentication token, or null if not authenticated.
- **fetchAccessToken** () => Promise - A function to fetch the current access token.
- **signIn** (provider: string, params?: FormData | Record & { redirectTo?: string; code?: string }) => Promise<{ signingIn: boolean; redirect?: URL }> - Function to initiate the sign-in process with a given provider and optional parameters.
- **signOut** () => Promise - Function to sign the user out.
```
--------------------------------
### Authenticated Data Operations in Svelte
Source: https://github.com/mmailaender/convex-auth-svelte/blob/main/src/lib/svelte/README.md
Use `useQuery` and `useConvexClient` from `convex-svelte` to interact with Convex backend. Queries automatically use the authenticated client. Mutations can be called directly via the client instance.
```svelte
{#if viewer.data}
Welcome, {viewer.data.name}!
{/if}
```
--------------------------------
### TokenStorage Interface
Source: https://github.com/mmailaender/convex-auth-svelte/blob/main/src/lib/svelte/README.md
Defines the interface for token storage mechanisms used by Convex Auth.
```APIDOC
## TokenStorage
### Description
An interface defining the methods required for storing and retrieving authentication tokens.
### Methods
- **getItem(key)**: (string) => string | undefined | null | Promise<...> - Retrieves an item from storage.
- **setItem(key, value)**: (string, string) => void | Promise - Sets an item in storage.
- **removeItem(key)**: (string) => void | Promise - Removes an item from storage.
```
--------------------------------
### Set E2E Test Secret in Convex Environment
Source: https://github.com/mmailaender/convex-auth-svelte/blob/main/e2e/README.md
Configure the necessary authentication secret for end-to-end tests within your Convex backend environment. Replace `` with your actual secret value.
```bash
npx convex env set AUTH_E2E_TEST_SECRET
```
--------------------------------
### Add Authentication Tables to Convex Schema
Source: https://github.com/mmailaender/convex-auth-svelte/blob/main/src/lib/svelte/README.md
Extend your Convex schema by importing and spreading `authTables` to include necessary authentication tables and indexes.
```typescript
// src/convex/schema.ts
import { defineSchema } from "convex/server";
import { authTables } from "@convex-dev/auth/server";
const schema = defineSchema({
...authTables,
// Your other tables...
});
export default schema;
```
--------------------------------
### SvelteKit Client-side Authenticated Data Operations
Source: https://github.com/mmailaender/convex-auth-svelte/blob/main/src/lib/sveltekit/README.md
Perform authenticated queries and mutations from the client-side in a SvelteKit application using Convex Svelte. Leverages `useQuery` and `useConvexClient` for seamless data fetching and manipulation.
```html
{#if viewer.data}
Welcome, {viewer.data.name}!
{/if}
```
--------------------------------
### Svelte Authentication UI with useAuth
Source: https://github.com/mmailaender/convex-auth-svelte/blob/main/src/lib/svelte/README.md
Use the `useAuth` hook to access authentication state (loading, authenticated) and control sign-in/sign-out actions within your Svelte components.
```svelte
{#if isLoading}
Loading authentication state...
{:else if isAuthenticated}
Welcome!
{:else}
Please sign in
{/if}
```
--------------------------------
### App-wide Auth: Blacklist Pattern (Public-first)
Source: https://github.com/mmailaender/convex-auth-svelte/blob/main/src/lib/sveltekit/README.md
Secure specific routes by defining protected paths and allowing access to all others by default. This hook-based approach is suitable when most routes are public.
```typescript
// src/hooks.server.ts
import { sequence } from '@sveltejs/kit/hooks';
import { redirect, type Handle } from '@sveltejs/kit';
import {
createConvexAuthHooks,
createRouteMatcher
} from '@mmailaender/convex-auth-svelte/sveltekit/server';
const isProtectedRoute = createRouteMatcher([
'/dashboard',
'/profile',
'/settings',
'/admin{/*rest}' // Protect all routes under /admin
]);
// Create auth hooks
const { handleAuth, isAuthenticated } = createConvexAuthHooks();
// Create custom auth handler
const protectRoutes: Handle = async ({ event, resolve }) => {
// Only check auth for protected routes
if (isProtectedRoute(event.url.pathname)) {
// Check if user is authenticated
if (!(await isAuthenticated(event))) {
// Redirect to signin if not authenticated
throw redirect(302, `/signin?redirectTo=${encodeURIComponent(event.url.pathname + event.url.search)}`);
}
}
// Allow access to all other routes
return resolve(event);
};
// Apply hooks in sequence
export const handle = sequence(
handleAuth,
protectRoutes
);
```
--------------------------------
### Use a Convex Query in React
Source: https://github.com/mmailaender/convex-auth-svelte/blob/main/src/lib/convex/README.md
Demonstrates how to call a Convex query function from a React component using the `useQuery` hook.
```typescript
const data = useQuery(api.functions.myQueryFunction, {
first: 10,
second: "hello",
});
```
--------------------------------
### Create Route Matcher for Path Matching
Source: https://context7.com/mmailaender/convex-auth-svelte/llms.txt
Utilize `createRouteMatcher` to generate functions for matching route pathnames using various patterns. This is essential for conditionally protecting routes in `hooks.server.ts`.
```typescript
import { createRouteMatcher } from '@mmailaender/convex-auth-svelte/sveltekit/server';
// Single path
const isSignIn = createRouteMatcher('/signin');
// Multiple paths
const isPublic = createRouteMatcher(['/signin', '/about', '/blog']);
// Named parameters
const isUserProfile = createRouteMatcher('/users/:id');
// Wildcard
const isAdminArea = createRouteMatcher('/admin/*path');
// Optional segment
const isProductPage = createRouteMatcher('/shop{/:category}/products');
// RegExp
const isLegacyRoute = createRouteMatcher(/^\/old-app\/.*/);
// Custom function
const isApiRoute = createRouteMatcher((pathname) => pathname.startsWith('/api/'));
// Usage in hooks
console.log(isPublic('/about')); // true
console.log(isAdminArea('/admin/settings')); // true
console.log(isUserProfile('/users/abc123')); // true
console.log(isPublic('/dashboard')); // false
```
--------------------------------
### Use a Convex Mutation in React
Source: https://github.com/mmailaender/convex-auth-svelte/blob/main/src/lib/convex/README.md
Shows how to invoke a Convex mutation function from a React component using the `useMutation` hook. Mutations can be fired and forgotten or their results can be awaited.
```typescript
const mutation = useMutation(api.functions.myMutationFunction);
function handleButtonPress() {
// fire and forget, the most common way to use mutations
mutation({ first: "Hello!", second: "me" });
// OR
// use the result once the mutation has completed
mutation({ first: "Hello!", second: "me" }).then((result) =>
console.log(result),
);
}
```
--------------------------------
### Page-level Protection using Page Server Load
Source: https://github.com/mmailaender/convex-auth-svelte/blob/main/src/lib/sveltekit/README.md
Protect individual pages by checking authentication status within the page server load function. Redirects unauthenticated users to the signin page.
```typescript
// src/routes/profile/+page.server.ts
import { createConvexAuthHandlers } from '@mmailaender/convex-auth-svelte/sveltekit/server';
import { redirect } from '@sveltejs/kit';
import type { PageServerLoad } from './$types';
// Create auth handlers
const { isAuthenticated } = createConvexAuthHandlers();
// Protect routes at the page level
export const load: PageServerLoad = async (event) => {
// Check if user is authenticated
if (!(await isAuthenticated(event))) {
// Redirect to signin if not authenticated
throw redirect(302, `/signin?redirectTo=${encodeURIComponent(event.url.pathname + event.url.search)}`);
}
// Return data for authenticated users
return {
user: { /* user data */ }
};
};
```
--------------------------------
### Define a Convex Query Function
Source: https://github.com/mmailaender/convex-auth-svelte/blob/main/src/lib/convex/README.md
Defines a query function with argument validation and database read operations. Use this for fetching data from Convex.
```typescript
// functions.js
import { query } from "./_generated/server";
import { v } from "convex/values";
export const myQueryFunction = query({
// Validators for arguments.
args: {
first: v.number(),
second: v.string(),
},
// Function implementation.
handler: async (ctx, args) => {
// Read the database as many times as you need here.
// See https://docs.convex.dev/database/reading-data.
const documents = await ctx.db.query("tablename").collect();
// Arguments passed from the client are properties of the args object.
console.log(args.first, args.second);
// Write arbitrary JavaScript here: filter, aggregate, build derived data,
// remove non-public properties, or create new objects.
return documents;
},
});
```
--------------------------------
### Define a Convex Mutation Function
Source: https://github.com/mmailaender/convex-auth-svelte/blob/main/src/lib/convex/README.md
Defines a mutation function with argument validation for modifying data in the database. Use this for writing data to Convex.
```typescript
// functions.js
import { mutation } from "./_generated/server";
import { v } from "convex/values";
export const myMutationFunction = mutation({
// Validators for arguments.
args: {
first: v.string(),
second: v.string(),
},
// Function implementation.
handler: async (ctx, args) => {
// Insert or modify documents in the database here.
// Mutations can also read from the database like queries.
// See https://docs.convex.dev/database/writing-data.
const message = { body: args.first, author: args.second };
const id = await ctx.db.insert("messages", message);
// Optionally, return a value from your mutation.
return await ctx.db.get(id);
},
});
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.