### Execute Project Setup and Management Commands Source: https://context7.com/joysofcode/sveltekit-remote-functions/llms.txt A collection of CLI commands for initializing the project, managing database schemas, and running the development server. These commands utilize pnpm and npx to streamline the workflow. ```bash npx degit joysofcode/sveltekit-remote-functions example pnpm install pnpm run db:push pnpm run dev pnpm run db:migrate pnpm run db:studio ``` -------------------------------- ### Initialize Database Connection Source: https://context7.com/joysofcode/sveltekit-remote-functions/llms.txt Sets up the Drizzle ORM connection using the libSQL client. Validates the presence of the DATABASE_URL environment variable before initializing. ```typescript import { drizzle } from 'drizzle-orm/libsql' import { createClient } from '@libsql/client' import { env } from '$env/dynamic/private' import * as schema from './schema' if (!env.DATABASE_URL) throw new Error('DATABASE_URL is not set') const client = createClient({ url: env.DATABASE_URL }) export const db = drizzle(client, { schema }) ``` -------------------------------- ### Configure Better Auth with Drizzle and SvelteKit Source: https://context7.com/joysofcode/sveltekit-remote-functions/llms.txt Initializes the Better Auth instance using the Drizzle adapter for SQLite and the SvelteKit cookies plugin. This setup enables email/password authentication and session cookie management. ```typescript import { betterAuth } from 'better-auth' import { drizzleAdapter } from 'better-auth/adapters/drizzle' import { sveltekitCookies } from 'better-auth/svelte-kit' import { db } from '$lib/server/database' import { getRequestEvent } from '$app/server' export const auth = betterAuth({ database: drizzleAdapter(db, { provider: 'sqlite' }), plugins: [sveltekitCookies(getRequestEvent)], emailAndPassword: { enabled: true } }) ``` -------------------------------- ### Configure Environment Variables Source: https://context7.com/joysofcode/sveltekit-remote-functions/llms.txt Defines the required environment variables for authentication and database connectivity. These should be placed in a .env file to ensure the application can access secrets and connection strings. ```bash BETTER_AUTH_SECRET=your-secret-key-here BETTER_AUTH_URL=http://localhost:3000 DATABASE_URL=file:local.db ``` -------------------------------- ### Fetch Data with Remote Functions Source: https://context7.com/joysofcode/sveltekit-remote-functions/llms.txt Demonstrates the use of remote query functions within Svelte 5 components using the await syntax to handle asynchronous data loading. ```svelte

Latest posts

{#each await getPosts() as post}
{post.title}
{:else}

No posts found

{/each}
``` -------------------------------- ### Execute Commands with Optimistic Updates Source: https://context7.com/joysofcode/sveltekit-remote-functions/llms.txt Implements optimistic UI updates by overriding the state of a remote function while the server processes the command request. ```svelte ``` -------------------------------- ### Configure Drizzle ORM Database Schema Source: https://context7.com/joysofcode/sveltekit-remote-functions/llms.txt Defines the SQLite database structure including users, posts, and comments tables with automatic timestamping. Uses Drizzle ORM to manage relationships and constraints. ```typescript import { sql } from 'drizzle-orm' import { sqliteTable, text, integer } from 'drizzle-orm/sqlite-core' const timestamps = { createdAt: integer('created_at', { mode: 'timestamp' }) .default(sql`(current_timestamp)`) .notNull(), updatedAt: integer('updated_at', { mode: 'timestamp' }) .default(sql`(current_timestamp)`) .$onUpdate(() => new Date()) .notNull(), } export const user = sqliteTable('user', { id: text('id').primaryKey(), name: text('name').notNull(), email: text('email').notNull().unique(), emailVerified: integer('email_verified', { mode: 'boolean' }).default(false).notNull(), image: text('image'), ...timestamps, }) export const posts = sqliteTable('posts', { id: integer('id').primaryKey({ autoIncrement: true }), authorId: text('author_id') .references(() => user.id, { onDelete: 'cascade' }) .notNull(), title: text('title').notNull(), slug: text('slug').notNull(), content: text('content'), likes: integer('likes').default(0), ...timestamps, }) export const comments = sqliteTable('comments', { id: integer('id').primaryKey({ autoIncrement: true }), postId: integer('post_id') .references(() => posts.id, { onDelete: 'cascade' }) .notNull(), author: text('author').notNull(), comment: text('comment').notNull(), ...timestamps, }) ``` -------------------------------- ### Implement SvelteKit Server Hooks for Auth Source: https://context7.com/joysofcode/sveltekit-remote-functions/llms.txt Configures the server handle hook to intercept requests, verify sessions via Better Auth, and populate event locals with user session data. ```typescript import { svelteKitHandler } from 'better-auth/svelte-kit' import { auth } from '$lib/server/auth' import { building } from '$app/environment' import type { Handle } from '@sveltejs/kit' export const handle: Handle = async ({ event, resolve }) => { const session = await auth.api.getSession({ headers: event.request.headers, }) if (session) { event.locals.session = session.session event.locals.user = session.user } return svelteKitHandler({ event, resolve, auth, building }) } ``` -------------------------------- ### Expose REST API Endpoints Source: https://context7.com/joysofcode/sveltekit-remote-functions/llms.txt Wraps remote functions in standard SvelteKit server endpoints to provide a RESTful interface for external clients. ```typescript import { getPosts } from '$lib/api/posts.remote' import { json } from '@sveltejs/kit' export async function GET() { const posts = await getPosts() return json(posts) } ``` ```bash curl http://localhost:5173/api/posts ``` -------------------------------- ### Define Zod Validation Schemas Source: https://context7.com/joysofcode/sveltekit-remote-functions/llms.txt Defines strict validation rules for post creation, updates, and comments using Zod. Includes regex-based slug validation and data transformation for ID fields. ```typescript import { z } from 'zod/mini' const slugRegex = /^[a-z0-9]+(?:-[a-z0-9]+)*$/ export const createPostSchema = z.object({ title: z.string(), slug: z.string().check(z.regex(slugRegex)), content: z.string(), }) export const updatePostSchema = z.object({ id: z.pipe( z.string(), z.transform((id) => Number(id)) ), title: z.string(), slug: z.string().check(z.regex(slugRegex)), content: z.string(), }) export const postCommentSchema = z.object({ postId: z.pipe( z.string(), z.transform((id) => Number(id)) ), author: z.string(), comment: z.string().check(z.minLength(2)), }) ``` -------------------------------- ### Handle Forms with Remote Validation Source: https://context7.com/joysofcode/sveltekit-remote-functions/llms.txt Uses remote form functions to bind input fields, display validation issues, and manage submission states in a Svelte component. ```svelte
``` -------------------------------- ### Authentication Schemas (TypeScript) Source: https://context7.com/joysofcode/sveltekit-remote-functions/llms.txt Defines Zod schemas for validating authentication form data (signup and login). Ensures type-safe data handling on both the client and server sides, enforcing rules like minimum length for passwords and valid email formats. ```typescript import { z } from 'zod/mini' export const signupSchema = z.object({ name: z.string().check(z.minLength(4)), email: z.email(), password: z.string().check(z.minLength(8)), }) export const loginSchema = z.object({ email: z.email(), password: z.string().check(z.minLength(8)), }) ``` -------------------------------- ### Posts Remote Functions - Query Operations (TypeScript) Source: https://context7.com/joysofcode/sveltekit-remote-functions/llms.txt Implements remote query functions for fetching blog post data. Supports fetching all posts, posts by a specific author (requires authentication), individual posts by slug with 404 handling, post like counts, and comments associated with a post. Uses Drizzle ORM for database interactions. ```typescript import { error, redirect } from '@sveltejs/kit' import { query } from '$app/server' import { eq } from 'drizzle-orm' import { z } from 'zod/mini' import { db } from '$lib/server/database' import * as table from '$lib/server/database/schema' // Get all posts (public) export const getPosts = query(async () => { const posts = await db.select().from(table.posts) return posts }) // Get posts by authenticated author (protected) export const getAuthorPosts = query(async () => { const user = requireAuth() const posts = await db.select().from(table.posts).where(eq(table.posts.authorId, user.id)) return posts }) // Get single post by slug with 404 handling export const getPost = query(z.string(), async (slug) => { const [post] = await db.select().from(table.posts).where(eq(table.posts.slug, slug)) if (!post) error(404, 'Post not found') return post }) // Get like count for a post export const getPostLikes = query(z.number(), async (id) => { const [{ likes }] = await db .select({ likes: table.posts.likes }) .from(table.posts) .where(eq(table.posts.id, id)) return likes ?? 0 }) // Get comments for a post export const getPostComments = query(z.number(), async (id) => { const comments = await db.select().from(table.comments).where(eq(table.comments.postId, id)) return comments }) ``` -------------------------------- ### Authentication Remote Functions (TypeScript) Source: https://context7.com/joysofcode/sveltekit-remote-functions/llms.txt Provides type-safe remote functions for user authentication (signup, login, signout) and session management. Utilizes Better Auth for authentication, Zod for schema validation, and SvelteKit's form and query utilities for seamless client-server interaction and redirects. ```typescript import { redirect } from '@sveltejs/kit' import { form, getRequestEvent, query } from '$app/server' import { auth } from '$lib/server/auth' import { signupSchema, loginSchema } from '$lib/schema/auth' // User signup with email and password export const signup = form(signupSchema, async (user) => { await auth.api.signUpEmail({ body: user }) redirect(307, `/admin`) }) // User login with email and password export const login = form(loginSchema, async (user) => { const { request } = getRequestEvent() await auth.api.signInEmail({ body: user, headers: request.headers }) redirect(303, '/admin') }) // User signout export const signout = form(async () => { const { request } = getRequestEvent() await auth.api.signOut({ headers: request.headers }) redirect(303, '/') }) // Get current authenticated user or redirect to login export const getUser = query(async () => { const { locals } = getRequestEvent() if (!locals.user) { redirect(307, '/auth/login') } return locals.user }) ``` -------------------------------- ### Generate RSS Feed Endpoint in SvelteKit Source: https://context7.com/joysofcode/sveltekit-remote-functions/llms.txt Creates an XML RSS feed by fetching post data via remote functions and formatting it into a standard RSS structure. It returns a Response object with the appropriate application/xml content type header. ```typescript import { getPosts } from '$lib/api/posts.remote' const site = { title: 'Svelte Tricks', description: 'Latest Svelte tips and tricks', url: 'http://localhost:5173/', } export async function GET() { const posts = await getPosts() const xml = ` ${site.title} ${site.description} ${site.url} ${posts .reverse() .map( (post) => ` ${post.title} ${post.content} ${site.url}${post.slug} ${site.url}${post.slug} ${new Date(post.createdAt).toUTCString()} ` ) .join('')} `.trim() return new Response(xml, { headers: { 'Content-Type': 'application/xml' } }) } ``` -------------------------------- ### Manage Post Mutations with Remote Functions Source: https://context7.com/joysofcode/sveltekit-remote-functions/llms.txt Handles server-side form submissions and command operations including authentication, database mutations, and optimistic UI updates. Utilizes SvelteKit's remote function utilities to manage post lifecycle and comments. ```typescript import { form, command, getRequestEvent } from '$app/server' import { eq, sql } from 'drizzle-orm' import { db } from '$lib/server/database' import * as table from '$lib/server/database/schema' import { updatePostSchema, postCommentSchema, createPostSchema } from '$lib/schema/posts' import { delay } from '$lib/utils' function requireAuth() { const { locals } = getRequestEvent() if (!locals.user) { redirect(307, '/auth/login') } return locals.user } export const createPost = form(createPostSchema, async (post) => { await delay(300) const user = requireAuth() await db.insert(table.posts).values({ ...post, authorId: user.id }) redirect(303, `/admin/edit/${post.slug}`) }) export const updatePost = form(updatePostSchema, async ({ id, title, slug, content }) => { await delay(300) await db.update(table.posts).set({ title, slug, content }).where(eq(table.posts.id, id)) }) export const removePost = form(updatePostSchema, async ({ id }) => { await delay(300) await db.delete(table.posts).where(eq(table.posts.id, id)) redirect(303, `/admin`) }) export const likePost = command(z.number(), async (id) => { await delay(2000) await db .update(table.posts) .set({ likes: sql`${table.posts.likes} + 1` }) .where(eq(table.posts.id, id)) getPostLikes(id).refresh() }) export const postComment = form(postCommentSchema, async (comment) => { await delay(300) await db.insert(table.comments).values(comment) }) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.