SvelteKit
01 / 02

File-Based Routing, Layouts & Load Functions

File-Based Routing, Layouts & Load Functions

Svelte Compiles Away; SvelteKit Adds the App

Svelte compiles components to targeted, imperative vanilla JS at build time — no virtual DOM diffing at runtime, unlike React. SvelteKit is the official app framework on top (routing, SSR, deployment), the same relationship Next.js has to React.

Route Structure

src/routes/
  +layout.svelte          # wraps every page — header/nav/footer
  +page.svelte            # renders at /
  about/+page.svelte      # renders at /about
  blog/[slug]/+page.svelte    # renders at /blog/hello-world, params.slug = "hello-world"
  blog/[slug]/+page.js         # universal load() for this page
  blog/[slug]/+page.server.js  # server-only load() — DB access, secrets
  api/posts/+server.js     # pure API endpoint, no UI

Folder structure IS the URL structure — no central route config. +layout.svelte nests (root layout + deeper section-specific layouts). +server.js gives a full-stack app both pages and API routes in one codebase.

load Functions

// +page.server.js
export async function load({ params }) {
  const post = await db.posts.findBySlug(params.slug);
  if (!post) throw error(404, 'Not found');
  return { post };
}

Data loads BEFORE the page renders — no loading-spinner flash, and when load runs server-side, the data ships inline in the initial HTML instead of needing a second browser round-trip. error()/fail() express expected failures (404, validation) distinctly from real server crashes.

Keep your own version of these notes — editable, searchable, and organised by your stack.

Start free