Svelte logoSveltev3INTERMEDIATE

SvelteKit

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

10 min read
sveltekitsveltessrssgroutingapifullstackvite
First page of the SvelteKit PDF cheat sheet

PDF · 2 pages

SvelteKit PDF cheat sheet

A two-page SvelteKit reference for printing or offline use.

Open PDF

Other Svelte Sheets

Loading your progress

Setup & Project Structure

Getting started with SvelteKit

Creating a new SvelteKit project

bash
# Create new SvelteKit app
npx sv create my-app
cd my-app
npm install          # if you skipped it during create
npm run dev          # http://localhost:5173

# sv create asks for
#   Template:  minimal, demo or library
#   Types:     TypeScript, JSDoc or none
#   Add-ons:   prettier, eslint, vitest, playwright,
#              tailwindcss, drizzle, sveltekit-adapter
🚀 Built on Vite for lightning-fast HMR
📦 SvelteKit 3 needs Node 22.17+, Vite 8 and Svelte 5
🔧 npx sv add sets up adapters, Tailwind, testing and more
⚡ npx sv migrate sveltekit-3 upgrades a SvelteKit 2 app

SvelteKit file and folder organization

javascript
my-app/
├── src/
│   ├── routes/          # File-based routing
│   ├── lib/             # Shared code (#lib alias)
│   ├── app.html         # HTML template
│   ├── app.d.ts         # TypeScript definitions
│   ├── env.js           # Environment variable declarations
│   └── params.js        # Route param matchers
├── static/              # Static assets
├── tests/               # Playwright tests (if added)
├── package.json         # "imports" defines #lib
└── vite.config.js       # Vite + SvelteKit config
📁 File-based routing in src/routes
🔗 #lib alias for src/lib, declared in package.json imports
🎯 Special +page/+layout naming convention
⚙️ SvelteKit config lives in vite.config.js, not svelte.config.js

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 uses plain links
<a href="/about">About</a>
<a href="/blog/my-post">Blog Post</a>
📁 File-based routing with folders and +page.svelte
🎯 Dynamic routes with [param], [...rest] and [[optional]]
📌 Read the current URL from page in $app/state
⚡ Built-in preloading with data-sveltekit-* attributes

Layouts

Nested layouts and layout groups

javascript
<!-- +layout.svelte -->
<script>
  let { data, children } = $props();
</script>

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

{@render children()}

<footer>© My App</footer>
🎨 Nested layouts inherit from parent layouts
📦 Layout groups with (folder) for organization
🔄 Layout resets with @ syntax
⚡ Layouts render the page with {@render children()}

Data Loading

Loading data in pages and layouts

Load functions that run on both client and server

javascript
// src/routes/blog/[slug]/+page.js
export async function load({ params, fetch }) {
  const res = await fetch(`/api/posts/${params.slug}`);
  const post = await res.json();

  return {
    post,
    title: post.title
  };
}

// src/routes/blog/[slug]/+page.svelte
<script>
  let { data } = $props();
</script>

<h1>{data.title}</h1>
🔄 Runs on the server first, then in the browser
🎯 Use the fetch passed to load for relative URLs and cookies
📦 Can set response headers and dependencies
⚡ Automatic type safety with TypeScript

Server-only load functions with direct database access

javascript
// +page.server.js
import { error } from '@sveltejs/kit';
import { db } from '#lib/server/database.js';

export async function load({ params }) {
  const post = await db.post.findUnique({
    where: { slug: params.slug }
  });

  if (!post) error(404, 'Post not found');

  return {
    post
  };
}
🔒 Runs only on server with access to secrets
🗄️ Direct database access without API calls
🍪 Full access to cookies and headers
⚡ Return a promise without await to stream it

Form Actions

Progressive form handling and mutations

Basic Actions

Server-side form handling

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

export const actions = {
  default: async ({ request }) => {
    const data = await request.formData();
    const email = data.get('email');

    if (!email) {
      return fail(400, { missing: true });
    }

    // Process form
    return { success: true };
  }
};

// +page.svelte
<script>
  let { form } = $props();
</script>

<form method="POST">
  {#if form?.missing}<p>Email is required</p>{/if}
  <input name="email" type="email" />
  <button>Submit</button>
</form>
📝 Progressive enhancement - works without JavaScript
🔒 Server-side validation with fail(status, data)
🍪 Direct cookie access for authentication
📌 A page has one default action or named actions, not both

Enhanced Forms

Client-side progressive enhancement

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

<form method="POST" use:enhance>
  <input name="title" />
  <button>Submit</button>
</form>
⚡ use:enhance for progressive enhancement
📌 use:enhance only works on forms with method="POST"
🎯 Optimistic UI updates without waiting
🔄 update() accepts reset, refreshAll and navigate options

API Routes

Creating API endpoints

Creating RESTful API endpoints

javascript
// +server.js
export async function GET() {
  return Response.json({ message: 'Hello' });
}

export async function POST({ request }) {
  const data = await request.json();
  return Response.json({ received: data }, { status: 201 });
}
🔗 RESTful endpoints with +server.js files
🔒 Access to cookies and authentication
📊 Full HTTP method support
📌 Return Response.json(), the json() helper is deprecated

Streaming & SSE

Server-sent events and streaming responses

javascript
// Streaming response (+server.js)
export async function GET() {
  const encoder = new TextEncoder();

  const stream = new ReadableStream({
    start(controller) {
      controller.enqueue(encoder.encode('Hello'));
      controller.close();
    }
  });

  return new Response(stream);
}
📡 Server-sent events for real-time updates
🌊 Streaming responses for large data
📦 NDJSON for streaming JSON data
⚠️ Platforms that buffer responses (AWS Lambda) cannot stream

Hooks

Server and client hooks for request handling

Server Hooks

Server-side request/response handling

javascript
// src/hooks.server.js
export async function handle({ event, resolve }) {
  // Runs for every request
  const response = await resolve(event);
  return response;
}
🔒 Authentication and authorization
🛡️ Security headers and CORS
📌 handleError({ kind, error, event }) receives every error
⚡ Transform responses before sending

Client Hooks

Client-side navigation and error handling

javascript
// src/hooks.client.js
export function handleError({ kind, error, event }) {
  if (kind !== 'unknown') return error;

  console.error(error);
  return { message: 'Something went wrong' };
}
❌ Client-side error handling and reporting
📊 Performance monitoring
💾 Service worker for offline support
🔄 reroute in src/hooks.js maps URLs to routes

Authentication

Implementing authentication patterns

Cookie-based authentication

javascript
// Login action (+page.server.js)
import { fail, redirect } from '@sveltejs/kit';
import { verifyUser, createSession } from '#lib/server/auth.js';

export const actions = {
  login: async ({ request, cookies }) => {
    const data = await request.formData();

    // Verify credentials
    const user = await verifyUser(data.get('email'), data.get('password'));
    if (!user) return fail(401, { incorrect: true });

    // httpOnly, secure and path '/' are the defaults
    const session = await createSession(user.id);
    cookies.set('session', session.id, {
      maxAge: 60 * 60 * 24 * 7
    });

    redirect(303, '/dashboard');
  }
};
🍪 Secure HTTP-only cookies for sessions
🔒 Server-side session validation
⚡ Automatic session extension
🛡️ Protected routes in hooks

Third-party authentication providers

javascript
// GitHub OAuth callback (+server.js)
import { error, redirect } from '@sveltejs/kit';
import { getGitHubToken, getGitHubUser } from '#lib/server/github.js';
import { createSession, findOrCreateUser } from '#lib/server/auth.js';

export async function GET({ url, cookies }) {
  const code = url.searchParams.get('code');
  const state = url.searchParams.get('state');

  // The state must match the cookie set before the redirect
  if (!state || state !== cookies.get('oauth_state')) {
    error(400, 'Invalid state');
  }

  // Exchange code for token
  const { access_token } = await getGitHubToken(code);

  // Get user info, then find or create the local user
  const githubUser = await getGitHubUser(access_token);
  const user = await findOrCreateUser(githubUser);

  // Create session
  const session = await createSession(user.id);
  cookies.set('session', session.id, { maxAge: 60 * 60 * 24 * 30 });

  redirect(303, '/');
}
🔑 OAuth with GitHub, Google, etc.
✉️ Magic link authentication
🛡️ CSRF protection with state parameter
📌 Redirects to another origin need { external: true }

Deployment

Building and deploying SvelteKit apps

Adapters

Deployment adapters for different platforms

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

// vite.config.js
import adapter from '@sveltejs/adapter-node';
import { sveltekit } from '@sveltejs/kit/vite';
import { defineConfig } from 'vite';

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

Optimizing SvelteKit apps for production

javascript
// Page options (+page.js, +page.server.js or +layout.js)
export const prerender = true;  // Generate at build time
export const ssr = true;        // Server-side rendering
export const csr = true;        // Client-side rendering

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

More Svelte Cheat Sheets