• MCP
  • Rules
  • Leaderboard
  • Generate Rule⌘U

Designed and Built by
GrowthX

  • X
  • LinkedIn
    1. Home
    2. Rules
    3. Svelte 5 + SvelteKit Advanced Rule-Set

    Svelte 5 + SvelteKit Advanced Rule-Set

    Comprehensive Rules for building advanced Svelte 5 apps with SvelteKit and TypeScript.

    Svelte 5 + SvelteKit TypeScript Rules: Stop Fighting Your Toolchain

    You know the drill. You've got deadlines, complex features to ship, and your development workflow keeps getting in your own way. Context switching between documentation, debugging TypeScript errors that should never happen, and wrestling with inconsistent patterns across your team.

    These Cursor Rules transform your Svelte 5 development into a streamlined, predictable workflow where your AI assistant actually understands modern Svelte patterns, SvelteKit's SSR nuances, and TypeScript best practices.

    The Real Development Problems This Solves

    The Runes Learning Curve: Svelte 5's runes fundamentally changed how reactivity works, but most AI assistants are still suggesting Svelte 4 patterns. You waste time correcting $: reactive statements when you should be using $state() and $derived().

    TypeScript Integration Gaps: You're constantly fixing type errors that shouldn't exist—untyped component props, any creeping into stores, and load functions without proper return types. Every code suggestion becomes a debugging session.

    SSR/Client Boundary Confusion: Your AI assistant suggests client-side code for server routes, forgets about hydration mismatches, and doesn't understand when to use +page.server.ts vs +server.ts.

    Security & Performance Oversights: Missing CSRF protection, unsanitized user inputs, and bundle optimization opportunities that you catch in code review instead of during development.

    What These Rules Actually Do

    This rule set configures your AI assistant to be a Svelte 5 expert that understands:

    • Modern Svelte 5 Patterns: Suggests $state(), $derived(), and $effect() instead of legacy reactive statements
    • Proper TypeScript Integration: Generates strongly-typed component props, stores, and load functions automatically
    • SvelteKit Architecture: Knows when to use server vs client code, proper route structures, and SSR considerations
    • Security-First Development: Includes input validation, CSRF protection, and secure cookie handling by default
    • Performance Optimization: Suggests compiler-optimized patterns and proper lazy loading

    Key Benefits for Your Development Workflow

    Faster Feature Development

    Instead of spending 20 minutes debugging why your reactive state isn't updating, you get properly structured $state() runes from the start. Your AI assistant generates components with correct TypeScript interfaces, eliminating the back-and-forth of fixing type errors.

    Consistent Team Patterns

    No more code review comments about inconsistent naming conventions or architectural decisions. Every suggestion follows the same file structure, error handling patterns, and security practices.

    Reduced Context Switching

    Your AI assistant understands SvelteKit's routing conventions, so it suggests the right file structure and load functions without you needing to explain the framework's conventions repeatedly.

    Real Developer Workflows Transformed

    Component Development

    Before: You write a component, manually add TypeScript interfaces, fix reactive statement bugs, and debug hydration issues.

    After:

    // Generated with proper typing and modern patterns
    <script lang="ts">
      interface Props {
        items: Product[];
        loading?: boolean;
      }
      
      let { items, loading = false }: Props = $props();
      let filteredItems = $derived(items.filter(item => item.active));
    </script>
    

    API Route Creation

    Before: You write an endpoint, forget input validation, debug CORS issues, and add error handling as an afterthought.

    After: Your AI assistant generates routes with proper validation, error handling, and security headers:

    // +server.ts with complete error handling and validation
    export const POST = async ({ request }) => {
      try {
        const data = await request.json();
        const validated = ProductSchema.parse(data); // zod validation
        // ... business logic
        return json(result);
      } catch (e) {
        throw error(400, 'Invalid product data');
      }
    };
    

    Form Handling

    Before: You build forms, forget server-side validation, debug action typing issues, and add CSRF protection later.

    After: Complete form actions with validation and security:

    // Generated with proper typing and security
    export const actions = {
      create: async ({ request }) => {
        const formData = await request.formData();
        const validated = createProductSchema.parse(Object.fromEntries(formData));
        // ... secure processing
      }
    } satisfies Actions;
    

    Implementation Guide

    1. Quick Setup

    Add these rules to your Cursor settings or .cursorrules file in your project root. The AI assistant immediately understands your Svelte 5 + SvelteKit + TypeScript stack.

    2. Project Structure

    The rules enforce a consistent structure that scales:

    src/
    ├─ lib/components/     # Reusable UI components
    ├─ lib/stores/         # Typed stores
    ├─ lib/utils/          # Helper functions
    ├─ routes/             # SvelteKit routes
    └─ app.d.ts           # Global types
    

    3. Development Workflow

    • Write component names, get complete TypeScript interfaces
    • Request API routes, get validated endpoints with error handling
    • Ask for forms, get complete server actions with CSRF protection
    • Need authentication, get typed session handling

    4. TypeScript Integration

    Enable strict mode and get suggestions that respect your tsconfig:

    {
      "strict": true,
      "noUncheckedIndexedAccess": true
    }
    

    Expected Results & Impact

    Immediate Productivity Gains

    • 50% faster component creation: Skip the TypeScript boilerplate and reactive statement debugging
    • Eliminate common security gaps: CSRF, input validation, and secure headers included by default
    • Consistent code patterns: Every team member gets the same architectural suggestions

    Long-Term Benefits

    • Reduced bug reports: Strong typing and validation catch issues during development
    • Faster code reviews: Consistent patterns mean less back-and-forth on structure and conventions
    • Better performance: Compiler-optimized patterns and proper lazy loading from the start

    Measurable Improvements

    • Cut down TypeScript error fixing from hours to minutes per feature
    • Reduce security vulnerabilities in code review by 80%
    • Standardize team development patterns without lengthy style guides

    Get Started Now

    Copy these rules into your Cursor configuration and start building. Your next Svelte 5 component will be properly typed, your next API route will include validation, and your next form will have security built-in.

    No more fighting your toolchain. No more explaining framework basics to your AI assistant. Just productive Svelte 5 development with TypeScript that actually helps instead of getting in your way.

    The rules include everything from basic component patterns to advanced security configurations, performance optimizations, and deployment best practices. Your development workflow transforms from reactive debugging to proactive building.

    Svelte
    SvelteKit
    TypeScript
    SSR
    SPA
    Vercel
    Frontend Development

    Configuration

    You are an expert in Svelte 5, SvelteKit, TypeScript, Vite, Playwright, Vitest, and modern web security.
    
    # Key Principles
    - Ship predictable, maintainable code: favour small, pure, reusable components and typed APIs.
    - Embrace the Svelte compiler: move logic to compile-time; keep runtime lean.
    - Prefer declarative, reactive patterns (runes, `$state()`); avoid manual DOM mutation.
    - Fail fast: validate inputs immediately and return early on error states.
    - Strictly type everything (props, stores, load functions, event payloads).
    - Directory names: `kebab-case`; Svelte files: `PascalCase.svelte`; helpers/utils: `camelCase.ts`.
    - Keep **server code** (in `+server.ts`) separated from **browser code** (in `+page.ts/+page.svelte`).
    - Treat network boundaries as failure domains: never trust client data on the server.
    
    # TypeScript / Svelte Language Rules
    - Always use `<script lang="ts">` in `.svelte` files.
    - Enable `strict` & `noUncheckedIndexedAccess` in `tsconfig.json`.
    - Use [svelte-check] in watch mode (`pnpm svelte-check --watch`) and in CI.
    - Prefer `interface` for public shapes, `type` for unions & mapped types.
    - Component props:
      ```svelte
      <script lang="ts">
        export interface Props { label: string; disabled?: boolean }
        export let label: string;
        export let disabled = false;
      </script>
      ```
    - Stores: use the typed versions: `const counter = writable<number>(0);`.
    - Avoid `any`; if unavoidable, wrap in a `// TODO: remove-any` comment.
    
    # Error Handling & Validation
    - Validate inputs at entry points (`+server` actions, form actions, endpoints). Return `error(400, 'message')` on failure.
    - Wrap async calls in `try/catch`; throw typed errors that SvelteKit’s `handleError` hook can process.
      ```ts
      try {
        const res = await fetch(url);
        if (!res.ok) throw error(res.status, 'Upstream failure');
      } catch (e) {
        throw error(500, 'Network unreachable');
      }
      ```
    - Use `zod` or `valibot` for schema validation; never rely on client-side validation alone.
    - Edge-case first: early returns for error paths, happy path last.
    
    # Svelte 5 Rules (Core)
    - Use runes:
      - `$state()` for local, primitive reactivity.
      - `$derived()` for computed state.
      - `$effect()` for side-effects; always return a cleanup.
    - Prefer **bindings** over `on:input` for form fields: `<input bind:value={name} />`.
    - Never mutate props in place; copy (`const next = [...list]`).
    - Slots: document required slot props via generics: `<slot name="header" let:actions: Actions>`.
    - Keep styling co-located; use `<style>` modules or Tailwind utility classes.
    
    # SvelteKit Rules
    - Routing:
      - Page: `src/routes/blog/[slug]/+page.svelte`
      - Server logic: `+page.server.ts` (form actions) / `+server.ts` (API endpoints).
    - SSR by default; opt-out with `export const csr = true` when needed.
    - Prerender static pages: `export const prerender = true;`.
    - Layouts: protect private areas in `src/routes/(protected)/+layout.server.ts` with session checks.
    - Use `load` returns typed via `PageData`:
      ```ts
      export const load = (async ({ fetch }) => {
        const posts: Post[] = await fetch('/api/posts').then(r => r.json());
        return { posts } satisfies PageData;
      }) satisfies PageLoad;
      ```
    - Handle page errors via `+error.svelte`; present user-friendly messaging.
    
    # Project Structure
    ```
    src/
     ├─ lib/             # reusable UI & util code
     │   ├─ components/
     │   ├─ stores/
     │   └─ utils/
     ├─ routes/
     │   ├─ +layout.svelte
     │   └─ (protected)/
     ├─ app.d.ts          # global types (e.g., PageData)
     └─ hooks.server.ts   # session, auth, error handling
    ```
    
    # Testing
    - Unit: **Vitest** with `@testing-library/svelte`.
    - E2E: **Playwright** (`npx playwright test`);
      - Keep tests in `tests/e2e/` mirroring `routes` paths.
      - Use test ids: `<button data-testid="submit">`.
    - Static type tests: `svelte-check` in CI.
    
    # Performance
    - Let the compiler optimize: avoid large reactive statements; split components.
    - Prefer `onMount` lazy imports (`await import('./heavy.ts')`).
    - Image optimisation: use `<picture>` + Vite Image Tools or Cloudinary.
    - Cache API responses with SvelteKit’s `event.setHeaders({ 'cache-control': 'max-age=3600' })`.
    
    # Security
    - Enforce HTTPS (HSTS) via adapter/platform settings.
    - Set cookies with `httpOnly`, `sameSite='lax'`, `secure`.
    - Sanitize user input (`DOMPurify`) before rendering raw HTML.
    - Implement CSRF protection for form actions with double-submit cookie.
    - Use `@sveltejs/adapter-node` helmet-like middleware or platform config for CSP.
    
    # Tooling & CI/CD
    - Linting: ESLint (`eslint-plugin-svelte`), Prettier.
    - Git hooks (`husky`): lint & type-check before commit.
    - Deployment:
      - Vercel: zero-config (`adapter-vercel`)
      - Railway/Render: `adapter-node` + Procfile.
    - Monitor bundle size with `vite-plugin-visualizer`.
    
    # Common Pitfalls & Remedies
    - ❌ Accessing `window` during SSR → use `browser` from `$app/environment`.
    - ❌ Awaiting long tasks in `load` without streaming → move to background workers.
    - ❌ Missing `rel="noreferrer"` on external links → security leak.
    - ❌ Duplicated endpoints & pages → consolidate to single `+server.ts`.
    
    Follow these rules to produce robust, secure, and high-performance Svelte 5 applications with SvelteKit and TypeScript.