Cursor Rules for
SvelteKit

This rule explains SvelteKit conventions and best practices for fullstack development.
Back to rules
Type
Fullstack
Language(s)
JavaScript
TypeScript
Tags
Framework
Stats
302 views
30 copies
12 downloads
sveltekit.mdc
---
description: This rule explains SvelteKit conventions and best practices for fullstack development.
globs: **/*.js,**/*.ts,**/*.svelte
alwaysApply: false
---

# SvelteKit rules

## File Structure
- Follow the file-based routing structure with `+page.svelte` for pages and `+layout.svelte` for layouts
- Use `+page.server.js` for server-only code including data loading and form actions
- Use `+server.js` files for API endpoints
- Place reusable components in `$lib/components/` using kebab-case directories
- Store utility functions in `$lib/utils/` and types in `$lib/types/`

## Component Patterns
- Use PascalCase for component filenames (e.g., `Button.svelte`)
- Prefer named exports over default exports
- Use TypeScript in components with `<script lang="ts">`
- Keep components small and focused on a single responsibility
- Use props validation with TypeScript interfaces

## Routing & Navigation
- Prefer SvelteKit's `<a>` links over programmatic navigation when possible
- Use route parameters with proper typing in load functions
- Implement nested layouts for sections sharing UI elements
- Use `+page.js` for client-side data loading that doesn't need server access

## Data Fetching
- Use `load` functions in `+page.server.js` for server-side data fetching
- Return properly typed data from load functions
- Implement error handling with try/catch and proper status codes
- Use `depends()` to mark cache dependencies between routes

## Form Handling
- Use SvelteKit's form actions with progressive enhancement
- Implement proper validation for both client and server
- Use `use:enhance` for enhanced form experiences while maintaining no-JS fallbacks
- Return useful validation errors to display in the UI

## State Management
- Use URL state for shareable data with `$page.url.searchParams`
- Use local state ($state) for component-specific state
- Use Svelte stores for shared application state
- Implement context and setContext/getContext for component trees

## Authentication & Authorization
- Handle authentication in hooks.server.js
- Use session cookies instead of localStorage for auth tokens
- Implement proper redirect logic for protected routes
- Create a custom auth helper for checking permissions

## Error Handling
- Create customized error pages with `+error.svelte`
- Use try/catch with proper error responses in server functions
- Implement global error handling for unexpected errors
- Provide user-friendly error messages

## Performance
- Minimize use of client-side JavaScript with server components
- Implement server-side rendering for SEO and performance
- Use `<script context="module">` for shared module code
- Implement proper caching strategies for API requests

## Deployment
- Use adapter-auto or specific adapters based on hosting platform
- Configure environment variables properly for different environments
- Implement proper build and optimization settings in svelte.config.js
- Use proper Content-Security-Policy headers

The SvelteKit rule provides comprehensive guidance on SvelteKit conventions and best practices for fullstack development in the Cursor editor. It helps ensure your SvelteKit projects follow recommended patterns for file structure, components, routing, data handling, and more.

What this rule does

This rule serves as a reference guide for working with SvelteKit applications in Cursor. It covers essential aspects of SvelteKit development including:

  • File structure and organization
  • Component patterns and naming conventions
  • Routing and navigation techniques
  • Data fetching strategies
  • Form handling approaches
  • State management options
  • Authentication and authorization implementation
  • Error handling best practices
  • Performance optimization techniques
  • Deployment considerations

The rule encapsulates industry best practices for SvelteKit development to help maintain consistency and follow established patterns.

Key SvelteKit conventions

File structure

SvelteKit uses a file-based routing system where:

  • +page.svelte files define page components
  • +layout.svelte files define layout components
  • +page.server.js files contain server-only code for data loading and form actions
  • +server.js files define API endpoints

The rule recommends organizing reusable components in $lib/components/ with kebab-case directories, while utilities and types should go in dedicated folders ($lib/utils/ and $lib/types/).

Component practices

The rule provides guidance on component naming and structure:

  • Use PascalCase for component filenames (e.g., Button.svelte)
  • Prefer TypeScript with <script lang="ts">
  • Keep components small and focused
  • Use proper props validation through TypeScript interfaces

Data and state management

SvelteKit provides several options for handling data and state:

  • Use load functions in +page.server.js for server-side data fetching
  • Implement Svelte stores for shared application state
  • Use URL state for shareable data
  • Utilize local state ($state) for component-specific state

Using SvelteKit in Cursor

The SvelteKit rule (sveltekit.mdc) is designed to be automatically attached when working with relevant files in your SvelteKit project. Based on the glob pattern (**/*.js,**/*.ts,**/*.svelte), this rule will be activated whenever you're working with JavaScript, TypeScript, or Svelte files.

When the rule is active, Cursor's AI will have context about SvelteKit conventions and best practices, allowing it to:

  1. Provide more accurate code suggestions aligned with SvelteKit conventions
  2. Offer context-aware completions when working with SvelteKit components and files
  3. Help troubleshoot issues by referencing SvelteKit patterns
  4. Assist with implementing SvelteKit-specific features correctly

You can also manually invoke this rule by typing @sveltekit in the chat or Cmd-K prompt if you need to explicitly request SvelteKit-focused assistance.

Usage tips

When building new components

When creating new components in your SvelteKit application, remember to:

<script lang="ts">
  // Define interfaces for your props
  interface Props {
    title: string;
    description?: string;
  }
  
  // Use destructuring with defaults for optional props
  export let title: Props['title'];
  export let description: Props['description'] = '';
</script>

<div class="component">
  <h2>{title}</h2>
  {#if description}
    <p>{description}</p>
  {/if}
</div>

For page routing

When implementing routing in SvelteKit, follow these patterns:

<!-- Use regular anchor tags for navigation -->
<a href="/about">About</a>

<!-- For programmatic navigation -->
<script>
  import { goto } from '$app/navigation';
  
  function handleClick() {
    goto('/dashboard');
  }
</script>

For form handling

SvelteKit offers progressive enhancement for forms:

<script>
  import { enhance } from '$app/forms';
</script>

<form method="POST" use:enhance>
  <input name="email" type="email" required>
  <button type="submit">Subscribe</button>
</form>

By following the conventions outlined in this rule, you'll create more maintainable, performant, and user-friendly SvelteKit applications while benefiting from Cursor's AI-powered assistance.

Want to 10x your AI skills?

Get a free account and learn to code + market your apps using AI (with or without vibes!).

Nah, maybe later