Overview
SvelteKit is a full-stack framework built on Svelte's compiler-first approach, shipping minimal JavaScript with no virtual DOM runtime. It provides file-based routing for pages and API endpoints, server-side form actions with progressive enhancement, and deployment adapters for any hosting platform. This skill targets SvelteKit 3 (@sveltejs/kit 3.x, with Svelte 5 runes); where a project is still on 2.x the differences are called out.
Instructions
- When creating a project, run
npx sv create invoice-app(options:--template minimal|demo|library,--types ts,--add eslint vitest playwright tailwindcss sveltekit-adapter). Thennpm run devstarts the dev server on port 5173. - When setting up routing, use file-based conventions:
+page.sveltefor pages,+layout.sveltefor shared layouts,+server.tsfor API endpoints, and route groups(name)for shared layouts without URL impact. - When loading data, use
+page.server.tsfor server-only loading (database queries, secrets) and+page.tsfor universal loading. Keepload()functions thin and move business logic tosrc/lib/server/. - When handling forms, use server-side form actions in
+page.server.tswithfail()for validation errors andredirect()for success. Adduse:enhancefor progressive enhancement. In SvelteKit 3 an enhanced submission reports the status code passed tofail()instead of always 200. - When creating API routes, export
GET,POST,PUT,DELETEhandlers from+server.tsreturning aResponse. In v3json()andtext()from@sveltejs/kitare deprecated: useResponse.json(...)andnew Response(text). Useerror()for HTTP errors. - When configuring rendering, default to SSR, use
export const prerender = truefor static pages (marketing, docs, blog), andexport const ssr = falsefor client-only pages. - When adding middleware, use
src/hooks.server.tswith thehandlefunction for auth, logging, and redirects, andsequence()to compose hooks. In v3 theHandletype is imported from@sveltejs/kit/hooks(alongsidesequence), not@sveltejs/kit. - When deploying, choose the adapter:
adapter-auto(detects some platforms, cannot build for a self-hosted box),adapter-nodefor self-hosting (node build,HOST/PORTenv vars, default0.0.0.0:3000),adapter-staticfor full SSG, oradapter-vercel,adapter-cloudflare,adapter-netlify.
SvelteKit 3 setup and upgrade notes
- Configuration lives in
vite.config.ts: options formerly underconfig.kitinsvelte.config.jsare now top-level options of thesveltekit({...})Vite plugin (adapter,paths,csrf,compilerOptions).svelte.config.jsis no longer read. - The
$libalias is replaced by#lib, declared by you inpackage.jsonimports("#lib": "./src/lib/index.js","#lib/*": "./src/lib/*"). Imports need the file extension:#lib/server/tasks.js.sv createwrites this for new projects. $app/environmentbecame$app/env;$app/storesis gone (use$app/state:page,navigating,updated);baseandassetsfrom$app/pathsare gone (useresolve()andasset()).csrf.checkOriginis replaced bycsrf.trustedOrigins: ['https://billing.partner.dev']; CSRF protection is always on. Cross-origin form posts need aContent-Typeheader.error(status, message)takes a string message only; extra fields go in a third argument.redirect()to another origin needs{ external: true }.handleErrornow sees expected errors too.adapter-nodeno longer readsORIGIN: setpaths.originin the Vite config (for examplepaths: { origin: process.env.ORIGIN }) when the app sits behind a proxy that hides the host.adapter-verceldropped theedgeruntime.data-sveltekit-preload-data="off"is now"false".invalidateAllis deprecated in favour ofrefreshAll.- To migrate from 2.x, upgrade to the latest 2.x first, then run
npx sv migrate sveltekit-3.
Minimal form action, endpoint and hook
// src/routes/tasks/+page.server.ts
import { fail, redirect } from '@sveltejs/kit';
import { addTask, listTasks } from '#lib/server/tasks.js';
import type { Actions, PageServerLoad } from './$types';
export const load: PageServerLoad = async () => ({ tasks: listTasks() });
export const actions: Actions = {
create: async ({ request }) => {
const data = await request.formData();
const title = String(data.get('title') ?? '').trim();
if (title.length < 3) return fail(400, { title, error: 'Title needs 3+ characters' });
addTask(title);
redirect(303, '/tasks');
}
};
<!-- src/routes/tasks/+page.svelte -->
<script lang="ts">
import { enhance } from '$app/forms';
let { data, form } = $props();
</script>
<form method="POST" action="?/create" use:enhance>
<input name="title" value={form?.title ?? ''} />
<button>Add</button>
{#if form?.error}<p>{form.error}</p>{/if}
</form>
<ul>{#each data.tasks as task (task.id)}<li>{task.title}</li>{/each}</ul>
// src/routes/api/health/+server.ts
import type { RequestHandler } from './$types';
export const GET: RequestHandler = () => Response.json({ ok: true });
// src/hooks.server.ts
import { redirect } from '@sveltejs/kit';
import { sequence, type Handle } from '@sveltejs/kit/hooks';
const auth: Handle = async ({ event, resolve }) => {
if (event.url.pathname.startsWith('/tasks') && !event.cookies.get('session')) redirect(303, '/login');
return resolve(event);
};
const logging: Handle = async ({ event, resolve }) => resolve(event);
export const handle = sequence(logging, auth);
On 2.x use import type { Handle } from '@sveltejs/kit' and $lib/... instead. These files build and type-check with npm run build and npx svelte-check on SvelteKit 3.1.
Examples
Example 1: Build a CRUD app with form actions
User request: "Create a SvelteKit app with form-based task management"
Actions:
- Run
npx sv create task-app --template minimal --types ts --no-add-ons, thennpm install - Define routes for task list (
src/routes/tasks/+page.svelte) and detail (src/routes/tasks/[id]/+page.svelte) - Implement
load()in+page.server.tsto fetch tasks from the database through#lib/server/helpers - Add
create,updateanddeletenamed actions withfail(400, {...})validation (Zod works well here) - Enhance forms with
use:enhance; without JavaScript they still post and the page re-renders withform
Output: A full-stack task management app with progressive enhancement and server-side validation.
Example 2: Deploy a hybrid SvelteKit app
User request: "Set up a SvelteKit site with static marketing pages and dynamic dashboard"
Actions:
- Create marketing pages with
export const prerender = true - Build dashboard routes with SSR and
+page.server.tsfor authenticated data loading - Add an auth hook in
src/hooks.server.tsto protect/dashboardroutes - Pick the adapter in
vite.config.ts:adapter-nodefor a VPS (npm run build && node build) oradapter-vercel/adapter-cloudflarefor a platform
Output: A hybrid app with pre-rendered marketing pages and a server-rendered authenticated dashboard.
Guidelines
- Use
+page.server.tsfor data loading that touches databases or secrets; never expose credentials in+page.ts. Modules undersrc/lib/server/cannot be imported by client code. - Default to server-side form handling with actions; add
use:enhancefor progressive enhancement. - Use
export const prerender = trueon marketing pages, docs, and blog posts. - Keep
load()functions thin: fetch data and return it, move business logic tosrc/lib/server/. - Use route groups
(name)to share layouts without affecting URLs. - Set
data-sveltekit-preload-data="hover"on links for perceived-instant navigation. - Always handle the
formprop in+page.svelteto display validation errors after failed actions. - Behind a reverse proxy set
PROTOCOL_HEADER/HOST_HEADER(adapter-node) only when the proxy is trusted; spoofed headers break CSRF checks and client IP detection. - Remote functions are still experimental (opt in with
experimental.remoteFunctionsandcompilerOptions.experimental.async); prefer actions andloadfor production code.