SvelteKit Cheat Sheet
Jul 29, 2023
2 min read
File Structure
Server-side
+hook.server.svelte
: Server hooks+layout.svelte
: Shared layout with<slot>
+layout.server.js
: Load data for child routes+server.js
: API routes (no+page.svelte
needed)
Client-side
+page.server.js
: Load data and handle API requests+page.js
: Dynamic component+page.svelte
: Page content
Shared Modules
- Use
$lib
to access modules insrc/lib
Routing
- Optional parameters:
[[lang]]
- Regex match:
[color=hex]
- Route groups:
(authed)
- Layout break:
+page@[level].svelte
Data Loading
- Universal load:
+page.js
,+layout.js
- Server load:
+page.server.js
,+layout.server.js
- Access parent data:
const { parentData } = await parent();
- Invalidate data:
invalidate('/api/route')
- Manual invalidation:
depends('app:custom')
Accessing loaded data
html<script> export let data;</script><h1>{data.title}</h1>
Forms
Default Form Action
html<form method="POST"> <input name="description" /></form>
javascriptexport const actions = { default: async ({ request }) => { const data = await request.formData(); // Handle form submission }};
Named Form Actions
html<form method="POST" action="?/create">
javascriptexport const actions = { create: async ({ request }) => { // Handle create action }, delete: async ({ request }) => { // Handle delete action }};
Form Validation
javascriptimport { fail } from '@sveltejs/kit';export const actions = { default: async ({ request }) => { const data = await request.formData(); if (/* validation fails */) { return fail(400, { error: 'Validation error' }); } // Process form }};
Error Handling
javascriptimport { error } from '@sveltejs/kit';throw error(420, 'Enhance your calm');// Redirectimport { redirect } from '@sveltejs/kit';throw redirect(307, '/new-path');
Custom error page
Create +error.svelte
in the route directory.
Stores
javascriptimport { page, navigating, updated } from '$app/stores';
Hooks
javascript// hooks.server.jsexport async function handle({ event, resolve }) { // Pre-processing const response = await resolve(event); // Post-processing return response;}// Intercepting fetchesexport async function handleFetch({ event, request, fetch }) { // Modify fetch behavior return fetch(request);}
Environment Variables
- Server-only:
$env/static/private
,$env/dynamic/private
- Client-safe:
$env/static/public
,$env/dynamic/public
Navigation
javascriptimport { goto, preloadCode, preloadData } from '$app/navigation';goto('/path');preloadData('/path');// Programmatic navigationimport { goto } from '$app/navigation';goto('/blog/create');
Preloading
html<a href="/slow-page" data-sveltekit-preload-data>Preload</a>
Force page reload
html<a href="/reload" data-sveltekit-reload>Reload</a>
Progressive Enhancement
html<form use:enhance>
javascriptimport { enhance } from '$app/forms';// Custom enhance function<form use:enhance={({ form, data, action, cancel, submitter }) => { // Pre-submission logic return ({ result, update }) => { // Post-submission logic };}}>
Page Options
javascriptexport const ssr = false;export const csr = false;export const prerender = true;export const trailingSlash = 'always' | 'never' | 'ignore';
Cookies
javascriptexport function load({ cookies }) { const visited = cookies.get('visited'); cookies.set('visited', 'true', { path: '/' }); return { visited };}
API Routes (+server.js)
javascriptexport async function GET({ params, request }) { // Handle GET request}export async function POST({ request }) { const data = await request.json(); // Handle POST request}
Authentication
javascript// src/routes/(authed)/+layout.server.jsimport { redirect } from '@sveltejs/kit';export function load({ cookies, url }) { if (!cookies.get('logged_in')) { throw redirect(303, `/login?redirectTo=${url.pathname}`); }}
Svelte Transitions
html<script> import { fade, fly } from 'svelte/transition';</script><div transition:fade>Fading content</div><div transition:fly="{{ y: 200, duration: 2000 }}">Flying content</div>
Lifecycle
javascriptimport { onMount, onDestroy } from 'svelte';onMount(() => { // Component mounted});onDestroy(() => { // Component will be destroyed});
Event Handling
html<button on:click={handleClick}>Click me</button><script> function handleClick(event) { console.log('Button clicked', event); }</script>