Skip to content

Lesson 4 of 9 · 18m

SvelteKit Routing: Files Are Product Behavior

Filesystem routes, dynamic segments, route groups, layouts, and navigation behavior — organized so URLs stay durable.

SvelteKit routing looks simple because it is files and folders. The design work is not the syntax; it is deciding which parts of the product deserve durable URLs and which parts are transient UI state. If the user can reasonably refresh, share, or bookmark a view, the router should know about it.

The filesystem is the route table

src/routes/
  +layout.svelte
  +page.svelte                    -> /
  incidents/
    +page.svelte                  -> /incidents
    [id]/
      +page.svelte                -> /incidents/42
  (docs)/
    guide/
      +page.svelte                -> /guide

[id] is a dynamic parameter. (docs) is a route group: it organizes files without adding /docs to the URL. Groups are useful for different layouts — marketing chrome versus application chrome — not as a substitute for naming things well.

Layouts are persistent UI shells

<!-- src/routes/incidents/+layout.svelte -->
<script>
  let { children } = $props();
</script>

<div class="shell">
  <aside>Incident filters</aside>
  {@render children()}
</div>

Navigating from /incidents/1 to /incidents/2 keeps the layout instance alive and swaps the page. That is why scroll position, open panels, and websocket subscriptions sometimes survive navigation when you did not expect it — or fail to reset when you did. Layout persistence is intentional, not a leak.

<script>
  import { goto } from "$app/navigation";

  async function open(id) {
    await goto(`/incidents/${id}`);
  }
</script>

Use real <a href> links for navigation. goto is for state changes after an action completes, not for reimplementing anchor tags. Links give you middle-click, copy link, prefetching behavior, and accessibility semantics for free.

URL state is a feature decision

Filters, pagination, tabs, and search terms belong in ?query= parameters when users may share the result. Use page.url.searchParams from $app/state in modern SvelteKit, or accept parameters in load, then render links that preserve the relevant query string.

Field notes

  • Optional parameters and matchers exist, but do not build clever route patterns before product needs them. Boring URLs age better.
  • A route group can change layout inheritance without changing the URL; surprise layout bugs often start there.
  • Do not hide deep pages behind client-side modals if support staff need to paste exact URLs into tickets.
  • If browser Back behaves oddly, check whether you stored UI state locally that should have been in the URL.

Was this lesson helpful?

Sign in to rate