Comprehensive SvelteKit patterns for building full-stack applications with server-side rendering and API routes
# SvelteKit Full-Stack Development Guide for Google Antigravity
Master SvelteKit full-stack development with Google Antigravity's Gemini 3 engine. This comprehensive guide covers server-side rendering, API routes, form handling, and production deployment patterns.
## Project Configuration
```typescript
// svelte.config.js - SvelteKit configuration
import adapter from '@sveltejs/adapter-auto';
import { vitePreprocess } from '@sveltejs/vite-plugin-svelte';
/** @type {import('@sveltejs/kit').Config} */
const config = {
preprocess: vitePreprocess(),
kit: {
adapter: adapter(),
alias: {
'$components': 'src/lib/components',
'$stores': 'src/lib/stores',
'$utils': 'src/lib/utils',
'$types': 'src/lib/types'
},
csrf: {
checkOrigin: true
}
}
};
export default config;
```
## Server-Side Data Loading
```typescript
// src/routes/products/+page.server.ts
import type { PageServerLoad, Actions } from './$types';
import { error, fail, redirect } from '@sveltejs/kit';
import { db } from '$lib/server/database';
import { z } from 'zod';
const ProductSchema = z.object({
name: z.string().min(1).max(100),
price: z.number().positive(),
description: z.string().max(1000).optional()
});
export const load: PageServerLoad = async ({ url, locals }) => {
const page = parseInt(url.searchParams.get('page') ?? '1');
const limit = 20;
const offset = (page - 1) * limit;
const [products, total] = await Promise.all([
db.product.findMany({
take: limit,
skip: offset,
orderBy: { createdAt: 'desc' },
include: { category: true }
}),
db.product.count()
]);
return {
products,
pagination: {
page,
limit,
total,
pages: Math.ceil(total / limit)
}
};
};
export const actions: Actions = {
create: async ({ request, locals }) => {
if (!locals.user) {
throw redirect(303, '/login');
}
const formData = await request.formData();
const data = Object.fromEntries(formData);
const result = ProductSchema.safeParse({
name: data.name,
price: parseFloat(data.price as string),
description: data.description
});
if (!result.success) {
return fail(400, {
errors: result.error.flatten().fieldErrors,
values: data
});
}
await db.product.create({
data: {
...result.data,
userId: locals.user.id
}
});
return { success: true };
},
delete: async ({ request, locals }) => {
const formData = await request.formData();
const id = formData.get('id') as string;
const product = await db.product.findUnique({ where: { id } });
if (!product || product.userId !== locals.user?.id) {
throw error(403, 'Not authorized');
}
await db.product.delete({ where: { id } });
return { deleted: true };
}
};
```
## Reactive Stores Pattern
```typescript
// src/lib/stores/cart.ts
import { writable, derived } from 'svelte/store';
import { browser } from '$app/environment';
interface CartItem {
id: string;
name: string;
price: number;
quantity: number;
}
function createCartStore() {
const initial: CartItem[] = browser
? JSON.parse(localStorage.getItem('cart') ?? '[]')
: [];
const { subscribe, set, update } = writable<CartItem[]>(initial);
if (browser) {
subscribe(items => {
localStorage.setItem('cart', JSON.stringify(items));
});
}
return {
subscribe,
addItem: (item: Omit<CartItem, 'quantity'>) => {
update(items => {
const existing = items.find(i => i.id === item.id);
if (existing) {
return items.map(i =>
i.id === item.id ? { ...i, quantity: i.quantity + 1 } : i
);
}
return [...items, { ...item, quantity: 1 }];
});
},
removeItem: (id: string) => {
update(items => items.filter(i => i.id !== id));
},
updateQuantity: (id: string, quantity: number) => {
update(items =>
items.map(i => (i.id === id ? { ...i, quantity } : i))
);
},
clear: () => set([])
};
}
export const cart = createCartStore();
export const cartTotal = derived(cart, $cart =>
$cart.reduce((sum, item) => sum + item.price * item.quantity, 0)
);
```
## API Route Handlers
```typescript
// src/routes/api/products/+server.ts
import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { db } from '$lib/server/database';
export const GET: RequestHandler = async ({ url }) => {
const search = url.searchParams.get('q');
const category = url.searchParams.get('category');
const products = await db.product.findMany({
where: {
AND: [
search ? { name: { contains: search, mode: 'insensitive' } } : {},
category ? { categoryId: category } : {}
]
},
include: { category: true }
});
return json(products);
};
export const POST: RequestHandler = async ({ request, locals }) => {
if (!locals.user) {
throw error(401, 'Unauthorized');
}
const body = await request.json();
const product = await db.product.create({
data: { ...body, userId: locals.user.id }
});
return json(product, { status: 201 });
};
```
## Best Practices
Google Antigravity's Gemini 3 engine recommends these SvelteKit best practices: Use server-side load functions for data fetching to enable SSR and better SEO. Implement form actions for progressive enhancement without JavaScript. Leverage Svelte stores for client-side state management. Use TypeScript throughout for type safety. Implement proper error boundaries and loading states for robust user experiences.This Svelte prompt is ideal for developers working on:
By using this prompt, you can save hours of manual coding and ensure best practices are followed from the start. It's particularly valuable for teams looking to maintain consistency across their svelte implementations.
Yes! All prompts on Antigravity AI Directory are free to use for both personal and commercial projects. No attribution required, though it's always appreciated.
This prompt works excellently with Claude, ChatGPT, Cursor, GitHub Copilot, and other modern AI coding assistants. For best results, use models with large context windows.
You can modify the prompt by adding specific requirements, constraints, or preferences. For Svelte projects, consider mentioning your framework version, coding style, and any specific libraries you're using.