Svelte logoSveltev5INTERMEDIATE

SvelteKit

SvelteKit cheat sheet with routing, load functions, form actions, server-side rendering, and full-stack patterns with code examples.

10 min read
sveltekitsveltessrssgroutingapifullstackvite

Other Svelte Sheets

Sign in to mark items as known and track your progress.

Sign in

Setup & Project Structure

Getting started with SvelteKit

Installation & Setup

Creating a new SvelteKit project

bash
# Create new SvelteKit app
npm create svelte@latest my-app
cd my-app
npm install
npm run dev

# Project options during setup
✔ Skeleton project
✔ TypeScript
✔ ESLint
✔ Prettier
✔ Playwright (testing)
✔ Vitest (unit testing)
🚀 Built on Vite for lightning-fast HMR
📦 TypeScript support out of the box
🔧 Multiple adapter options for deployment
⚡ File-based routing with special naming conventions

Project Structure

SvelteKit file and folder organization

javascript
my-app/
├── src/
│   ├── routes/          # File-based routing
│   ├── lib/             # Shared utilities ($lib alias)
│   ├── app.html         # HTML template
│   └── app.d.ts         # TypeScript definitions
├── static/              # Static assets
├── tests/               # Test files
├── package.json
├── svelte.config.js     # SvelteKit config
└── vite.config.js       # Vite config
📁 File-based routing in src/routes
🔗 $lib alias for easy imports
🎯 Special +page/+layout naming convention
⚙️ Separate client and server hooks

Routing

File-based routing and navigation

Basic Routing

File-based routing patterns

javascript
// Route file structure
src/routes/
  +page.svelte       // index (/)
  +layout.svelte     // root layout
  about/+page.svelte // /about
  blog/
    +page.svelte     // /blog
    [slug]/
      +page.svelte   // /blog/:slug

// Navigation
<a href="/about">About</a>
<a href="/blog/my-post">Blog Post</a>
📁 File-based routing with folders and +page.svelte
🔗 Automatic code splitting per route
🎯 Dynamic routes with [param] syntax
⚡ Built-in preloading with data attributes

Layouts

Nested layouts and layout groups

javascript
<!-- +layout.svelte -->
<script>
  export let data;
</script>

<nav>
  <a href="/">Home</a>
  <a href="/about">About</a>
</nav>

<slot />

<footer>© 2024</footer>
🎨 Nested layouts inherit from parent layouts
📦 Layout groups with (folder) for organization
🔄 Layout resets with @ syntax
⚡ Layouts can have their own load functions

Data Loading

Loading data in pages and layouts

Universal Load Functions

Load functions that run on both client and server

javascript
// +page.js
export async function load({ params, url }) {
  const res = await fetch('/api/post/' + params.id);
  const post = await res.json();
  
  return {
    post,
    title: post.title
  };
}

// +page.svelte
<script>
  export let data;
</script>

<h1>{data.title}</h1>
🔄 Runs on both server and client
🎯 Access to special SvelteKit fetch
📦 Can set response headers and dependencies
⚡ Automatic type safety with TypeScript

Server Load Functions

Server-only load functions with direct database access

javascript
// +page.server.js
import { db } from '$lib/server/database';

export async function load({ params }) {
  const post = await db.post.findUnique({
    where: { slug: params.slug }
  });
  
  return {
    post
  };
}
🔒 Runs only on server with access to secrets
🗄️ Direct database access without API calls
🍪 Full access to cookies and headers
⚡ Can stream promises for faster initial render

Form Actions

Progressive form handling and mutations

Basic Actions

Server-side form handling

javascript
// +page.server.js
export const actions = {
  default: async ({ request }) => {
    const data = await request.formData();
    const email = data.get('email');
    
    // Process form
    return { success: true };
  }
};

// +page.svelte
<form method="POST">
  <input name="email" type="email" />
  <button>Submit</button>
</form>
📝 Progressive enhancement - works without JavaScript
🔒 Server-side validation and processing
🍪 Direct cookie access for authentication
⚡ use:enhance for optimistic UI updates

Enhanced Forms

Client-side progressive enhancement

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

<form use:enhance>
  <input name="title" />
  <button>Submit</button>
</form>
⚡ use:enhance for progressive enhancement
🎯 Optimistic UI updates without waiting
📝 Access to form data before submission
🔄 Custom result handling and validation

API Routes

Creating API endpoints

Server Endpoints

Creating RESTful API endpoints

javascript
// +server.js
import { json } from '@sveltejs/kit';

export async function GET() {
  return json({ message: 'Hello' });
}

export async function POST({ request }) {
  const data = await request.json();
  return json({ received: data });
}
🔗 RESTful endpoints with +server.js files
🔒 Access to cookies and authentication
📊 Full HTTP method support
⚡ Automatic error handling and status codes

Streaming & SSE

Server-sent events and streaming responses

javascript
// Streaming response
export async function GET() {
  const stream = new ReadableStream({
    start(controller) {
      controller.enqueue('Hello');
      controller.close();
    }
  });
  
  return new Response(stream);
}
📡 Server-sent events for real-time updates
🌊 Streaming responses for large data
📦 NDJSON for streaming JSON data
⚡ Efficient memory usage for large files

Hooks

Server and client hooks for request handling

Server Hooks

Server-side request/response handling

javascript
// hooks.server.js
export async function handle({ event, resolve }) {
  // Run before every request
  const response = await resolve(event);
  return response;
}
🔒 Authentication and authorization
🛡️ Security headers and CORS
📊 Request logging and monitoring
⚡ Transform responses before sending

Client Hooks

Client-side navigation and error handling

javascript
// hooks.client.js
export async function handleError({ error }) {
  console.error(error);
}
❌ Client-side error handling and reporting
📊 Performance monitoring
💾 Service worker for offline support
🔄 Handle navigation events

Authentication

Implementing authentication patterns

Session-based Auth

Cookie-based authentication

javascript
// Login action
export const actions = {
  login: async ({ request, cookies }) => {
    const data = await request.formData();
    
    // Verify credentials...
    
    cookies.set('session', sessionId, {
      path: '/',
      httpOnly: true,
      secure: true,
      maxAge: 60 * 60 * 24 * 7
    });
    
    throw redirect(303, '/dashboard');
  }
};
🍪 Secure HTTP-only cookies for sessions
🔒 Server-side session validation
⚡ Automatic session extension
🛡️ Protected routes in hooks

OAuth Integration

Third-party authentication providers

javascript
// GitHub OAuth example
export async function GET({ url, cookies }) {
  const code = url.searchParams.get('code');
  
  // Exchange code for token
  const { access_token } = await getGitHubToken(code);
  
  // Get user info
  const user = await getGitHubUser(access_token);
  
  // Create session
  cookies.set('session', sessionId, options);
  
  throw redirect(303, '/');
}
🔑 OAuth with GitHub, Google, etc.
✉️ Magic link authentication
🛡️ CSRF protection with state parameter
🔄 Account linking for existing users

Deployment

Building and deploying SvelteKit apps

Adapters

Deployment adapters for different platforms

javascript
// Node.js adapter
npm install -D @sveltejs/adapter-node

// svelte.config.js
import adapter from '@sveltejs/adapter-node';

export default {
  kit: {
    adapter: adapter()
  }
};
🚀 Multiple adapter options for different platforms
📦 Static site generation with adapter-static
☁️ Serverless deployment with Vercel/Netlify
🐳 Docker support with adapter-node

Performance Optimization

Optimizing SvelteKit apps for production

javascript
// Prerendering pages
export const prerender = true;
export const ssr = true;
export const csr = true;

// Preloading data
<a href="/about" data-sveltekit-preload-data>
  About
</a>
⚡ Prerendering for static pages
📦 Code splitting with dynamic imports
🖼️ Image lazy loading and optimization
📊 Core Web Vitals monitoring

More Svelte Cheat Sheets