SvelteKit
SvelteKit cheat sheet with routing, load functions, form actions, server-side rendering, and full-stack patterns with code examples.
Other Svelte Sheets
Sign in to mark items as known and track your progress.
Sign inSetup & Project Structure
Getting started with SvelteKit
Installation & Setup
Creating a new SvelteKit project
# 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)Project Structure
SvelteKit file and folder organization
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 configRouting
File-based routing and navigation
Basic Routing
File-based routing patterns
// 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>Layouts
Nested layouts and layout groups
<!-- +layout.svelte -->
<script>
export let data;
</script>
<nav>
<a href="/">Home</a>
<a href="/about">About</a>
</nav>
<slot />
<footer>© 2024</footer>Data Loading
Loading data in pages and layouts
Universal Load Functions
Load functions that run on both client and server
// +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>Server Load Functions
Server-only load functions with direct database access
// +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
};
}Form Actions
Progressive form handling and mutations
Basic Actions
Server-side form handling
// +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>Enhanced Forms
Client-side progressive enhancement
<script>
import { enhance } from '$app/forms';
</script>
<form use:enhance>
<input name="title" />
<button>Submit</button>
</form>API Routes
Creating API endpoints
Server Endpoints
Creating RESTful API endpoints
// +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 });
}Streaming & SSE
Server-sent events and streaming responses
// Streaming response
export async function GET() {
const stream = new ReadableStream({
start(controller) {
controller.enqueue('Hello');
controller.close();
}
});
return new Response(stream);
}Hooks
Server and client hooks for request handling
Server Hooks
Server-side request/response handling
// hooks.server.js
export async function handle({ event, resolve }) {
// Run before every request
const response = await resolve(event);
return response;
}Client Hooks
Client-side navigation and error handling
// hooks.client.js
export async function handleError({ error }) {
console.error(error);
}Authentication
Implementing authentication patterns
Session-based Auth
Cookie-based authentication
// 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');
}
};OAuth Integration
Third-party authentication providers
// 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, '/');
}Deployment
Building and deploying SvelteKit apps
Adapters
Deployment adapters for different platforms
// Node.js adapter
npm install -D @sveltejs/adapter-node
// svelte.config.js
import adapter from '@sveltejs/adapter-node';
export default {
kit: {
adapter: adapter()
}
};Performance Optimization
Optimizing SvelteKit apps for production
// 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>