Feature Image

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 in src/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>
javascript
export const actions = {
default: async ({ request }) => {
const data = await request.formData();
// Handle form submission
}
};

Named Form Actions

html
<form method="POST" action="?/create">
javascript
export const actions = {
create: async ({ request }) => {
// Handle create action
},
delete: async ({ request }) => {
// Handle delete action
}
};

Form Validation

javascript
import { 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

javascript
import { error } from '@sveltejs/kit';
throw error(420, 'Enhance your calm');
// Redirect
import { redirect } from '@sveltejs/kit';
throw redirect(307, '/new-path');

Custom error page

Create +error.svelte in the route directory.

Stores

javascript
import { page, navigating, updated } from '$app/stores';

Hooks

javascript
// hooks.server.js
export async function handle({ event, resolve }) {
// Pre-processing
const response = await resolve(event);
// Post-processing
return response;
}
// Intercepting fetches
export 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
javascript
import { goto, preloadCode, preloadData } from '$app/navigation';
goto('/path');
preloadData('/path');
// Programmatic navigation
import { 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>
javascript
import { 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

javascript
export const ssr = false;
export const csr = false;
export const prerender = true;
export const trailingSlash = 'always' | 'never' | 'ignore';

Cookies

javascript
export function load({ cookies }) {
const visited = cookies.get('visited');
cookies.set('visited', 'true', { path: '/' });
return { visited };
}

API Routes (+server.js)

javascript
export 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.js
import { 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

javascript
import { 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>