Svelte 5 & SvelteKit Expert
Expert guidance for building modern web applications with Svelte 5, SvelteKit, TypeScript, and best practices for SSR/SSG development.
Key Principles
Write concise, technical code with accurate Svelte 5 and SvelteKit examplesLeverage SvelteKit's server-side rendering (SSR) and static site generation (SSG) capabilitiesPrioritize performance optimization and minimal JavaScript for optimal user experienceUse descriptive variable names and follow Svelte and SvelteKit conventionsOrganize files using SvelteKit's file-based routing systemCode Style and Structure
Write concise, technical TypeScript or JavaScript code with accurate examplesUse functional and declarative programming patterns; avoid unnecessary classes except for state machinesPrefer iteration and modularization over code duplicationStructure files: component logic, markup, styles, helpers, typesFollow Svelte's official documentation for setup and configuration: https://svelte.dev/docsNaming Conventions
Use lowercase with hyphens for component files (e.g., `components/auth-form.svelte`)Use PascalCase for component names in imports and usageUse camelCase for variables, functions, and propsTypeScript Usage
Use TypeScript for all code; prefer interfaces over typesAvoid enums; use const objects insteadUse functional components with TypeScript interfaces for propsEnable strict mode in TypeScript for better type safetySvelte 5 Runes
Master the new Svelte 5 runes system:
**`$state`**: Declare reactive state
```typescript
let count = $state(0);
```
**`$derived`**: Compute derived values
```typescript
let doubled = $derived(count * 2);
```
**`$effect`**: Manage side effects and lifecycle
```typescript
$effect(() => {
console.log(`Count is now ${count}`);
});
```
**`$props`**: Declare component props
```typescript
let { optionalProp = 42, requiredProp } = $props();
```
**`$bindable`**: Create two-way bindable props
```typescript
let { bindableProp = $bindable() } = $props();
```
**`$inspect`**: Debug reactive state (development only)
```typescript
$inspect(count);
```
UI and Styling
Use Tailwind CSS for utility-first styling approachLeverage Shadcn components for pre-built, customizable UI elementsImport Shadcn components from `$lib/components/ui`Organize Tailwind classes using the `cn()` utility from `$lib/utils`Use Svelte's built-in transition and animation featuresShadcn Color Conventions
Define CSS variables without color space function:
```css
--primary: 222.2 47.4% 11.2%;
--primary-foreground: 210 40% 98%;
```
Usage example:
```svelte
<div class="bg-primary text-primary-foreground">Content</div>
```
SvelteKit Project Structure
Use the recommended structure:
```
src/
lib/
routes/
app.html
static/
svelte.config.js
vite.config.js
```
State Management
Use classes for complex state management (state machines):
```typescript
// counter.svelte.ts
class Counter {
count = $state(0);
incrementor = $state(1);
increment() {
this.count += this.incrementor;
}
resetCount() {
this.count = 0;
}
}
export const counter = new Counter();
```
Use in components:
```svelte
<script>
import { counter } from './counter.svelte.ts';
</script>
<button on:click={() => counter.increment()}>
Count: {counter.count}
</button>
```
Routing and Pages
Utilize SvelteKit's file-based routing system in the `src/routes/` directoryImplement dynamic routes using `[slug]` syntaxUse load functions for server-side data fetching and pre-renderingImplement proper error handling with `+error.svelte` pagesServer-Side Rendering (SSR) and Static Site Generation (SSG)
Leverage SvelteKit's SSR capabilities for dynamic contentImplement SSG for static pages using prerender optionUse the `adapter-auto` for automatic deployment configurationPerformance Optimization
Leverage Svelte's compile-time optimizationsUse `{#key}` blocks to force re-rendering of components when neededImplement code splitting using dynamic imports for large applicationsProfile and monitor performance using browser developer toolsUse `$effect.tracking()` to optimize effect dependenciesMinimize use of client-side JavaScript; leverage SvelteKit's SSR and SSGImplement proper lazy loading for images and other assetsData Fetching and API Routes
Use load functions for server-side data fetchingImplement proper error handling for data fetching operationsCreate API routes in the `src/routes/api/` directoryImplement proper request handling and response formatting in API routesUse SvelteKit's hooks for global API middlewareForms and Actions
Utilize SvelteKit's form actions for server-side form handlingImplement proper client-side form validation using Svelte's reactive declarationsUse progressive enhancement for JavaScript-optional form submissionsInternationalization (i18n)
Use Paraglide.js for internationalization:
Install: `npm install @inlang/paraglide-js`Set up language files in the `languages` directoryUse the `t` function to translate strings:```svelte
<script>
import { t } from '@inlang/paraglide-js';
</script>
<h1>{t('welcome_message')}</h1>
```
Support multiple languages and RTL layoutsEnsure text scaling and font adjustments for accessibilityAccessibility
Ensure proper semantic HTML structure in Svelte componentsImplement ARIA attributes where necessaryEnsure keyboard navigation support for interactive elementsUse Svelte's `bind:this` for managing focus programmaticallySecurity Best Practices
Only expose environment variables prefixed with `PUBLIC_` to the clientKeep sensitive variables server-side and access them only in server codeValidate and sanitize user inputsImplement proper CSRF protection using SvelteKit's built-in featuresKey Conventions
1. Embrace Svelte's simplicity and avoid over-engineering solutions
2. Use SvelteKit for full-stack applications with SSR and API routes
3. Prioritize Web Vitals (LCP, FID, CLS) for performance optimization
4. Use environment variables for configuration management
5. Follow Svelte's best practices for component composition and state management
6. Ensure cross-browser compatibility by testing on multiple platforms
7. Keep your Svelte and SvelteKit versions up to date
Documentation References
Svelte 5 Runes: https://svelte-5-preview.vercel.app/docs/runesSvelte Documentation: https://svelte.dev/docsSvelteKit Documentation: https://kit.svelte.dev/docsParaglide.js Documentation: https://inlang.com/m/gerre34r/library-inlang-paraglideJs/usageExample Component
```svelte
<script lang="ts">
import { cn } from '$lib/utils';
interface Props {
title: string;
count?: number;
}
let { title, count = 0 }: Props = $props();
let doubled = $derived(count * 2);
$effect(() => {
console.log(`Count changed to ${count}`);
});
function increment() {
count++;
}
</script>
<div class={cn("p-4 bg-primary text-primary-foreground rounded-lg")}>
<h2 class="text-xl font-bold">{title}</h2>
<p>Count: {count}</p>
<p>Doubled: {doubled}</p>
<button
class="mt-2 px-4 py-2 bg-white text-black rounded"
on:click={increment}
>
Increment
</button>
</div>
```
Refer to the official documentation for detailed information on components, internationalization, and best practices.