# SvelteKit fundamentals: routes and layouts

- Published: 2026-11-30
- Tags: Why Svelte, Svelte
- URL: https://devtrillo.com/writing/why-svelte-12-sveltekit-fundamentals-routes-and-layouts/

> Part 12 of a series on Svelte in 2026. [Part 11](/writing/why-svelte-11-scoped-styles-css-that-stays-put/) finished the language half with scoped styles. This part starts on SvelteKit: how a folder becomes a URL, how layouts nest, and what survives when you navigate.

I had a post page with a like button, and two posts, `a` and `b`. I liked `a`, clicked the link to `b`, and the button on `b` already said `liked true`. The heading said "Post b", which was right.

But a `title` variable I'd set in the script still said "Post a".

Nothing was broken. SvelteKit saw that `/posts/a` and `/posts/b` use the same `+page.svelte`, kept the component it already had mounted, and handed it new `data`.

Once you know it does that, routes and layouts stop being a file-naming convention and start being a component tree, one that stays mounted as long as it can.

## A folder is a URL

Every route lives under `src/routes`, and the folder path is the URL path. A `+page.svelte` in a folder makes that folder a page; the `+` prefix is how SvelteKit tells its files apart from yours.[^routing]

I put a plain `Thing.svelte` next to `about/+page.svelte`, and `/about/Thing` returned a 404, so your own components can sit in the route folder they belong to without becoming pages.

```txt
src/routes/
├── +layout.svelte          → wraps every page
├── +page.svelte            → /
├── about/+page.svelte      → /about
└── posts/
    ├── +layout.svelte      → wraps everything under /posts
    ├── +layout.ts          → data for that layout and its pages
    ├── new/+page.svelte    → /posts/new
    └── [slug]/
        ├── +page.ts        → loads one post
        └── +page.svelte    → /posts/a, /posts/b, …
```

Brackets make a parameter. `[slug]` matches any single segment, and the page gets it as `params.slug`.

`/posts/new` and `/posts/[slug]` both match `/posts/new`, and the static one won: SvelteKit sorts routes so that "more specific routes are higher priority."[^advanced]

I ran all of this on SvelteKit 3.1.0 with Svelte 5.57.2 and Vite 8.3.5, scaffolded with `sv create`.

If you're coming from SvelteKit 2, `+page` and `+layout` work the same; what moved is around them. `svelte.config.js` is gone (options go to the `sveltekit()` plugin in `vite.config.ts`), and `$lib` became a `#lib` entry in `package.json` imports.[^kit3] Part 15 covers the rest of the SvelteKit 3 changes.

## Layouts wrap, and stay

A `+layout.svelte` wraps every page in its folder and in every folder below it. "By default, each layout inherits the layout above it," so `/posts/a` renders inside the posts layout, which renders inside the root one.[^routing] The page arrives as the `children` prop, and the layout decides where it goes:

```svelte title="src/routes/posts/+layout.svelte"
<script lang="ts">
  import type { LayoutProps } from "./$types";

  let { data, children }: LayoutProps = $props();
  let open = $state(false);
</script>

<aside>
  <button onclick={() => (open = !open)}>filters {open}</button>
</aside>

{@render children()}
```

That `children` is a snippet, the same kind [part 7](/writing/why-svelte-7-children-is-a-function/) showed, and `{@render children()}` is "the only requirement" the docs place on a layout.[^routing]

Leave it out and the page doesn't render at all. I deleted it from a layout, `/pricing` came back as a 200 with the layout's markup and no page, and the dev server printed `layout_children_missing`: "inner content will not be rendered."

The reason to put things in a layout instead of importing a `<Nav>` on every page is what happens when you navigate.

I logged a message when each component mounted and when it was destroyed, then clicked through the app with Playwright 1.64.1. The root layout logged `mounted` once, on the first page, and never again. A counter in it, clicked twice on `/`, still said 2 after visits to `/about`, `/posts/a`, `/posts/b` and a dashboard.

The posts layout was the same inside its own folder: I opened its filter panel on `/posts/a`, and it was still open on `/posts/b` and on `/posts/new`.

Moving between sibling pages destroys the page and leaves every layout above it alone. Going from `/about` to `/posts/a` logged `ABOUT destroyed`, then mounts for the post page and the posts layout, and nothing for the root.

## Same route, same component

Here is the page from the opening:

```svelte title="src/routes/posts/[slug]/+page.svelte"
<script lang="ts">
  import type { PageProps } from "./$types";

  let { data }: PageProps = $props();
  let liked = $state(false);
  let title = data.title;
</script>

<h1>{data.title}</h1>
<p>{title}</p>
<button onclick={() => (liked = !liked)}>liked {liked}</button>
```

The docs say it straight: "SvelteKit reuses existing layout and page components."[^state] Going from `/posts/a` to `/posts/b` re-ran the page's `load` and logged no mount or destroy.

The component stayed, `data` changed, and anything that read `data` once at the top of the script kept the old value: `<h1>` showed "Post b", `<p>` showed "Post a", and `liked` stayed true.

You've seen `let title = data.title` before. It's [part 6's](/writing/why-svelte-6-props-are-getters/) stale prop, and svelte-check 4.7.7 flagged it with the same `state_referenced_locally` warning. The fix is the same too: `let title = $derived(data.title)`.

`liked` is harder, because it's state the page owns, and whether it should reset is your call. If it should, wrap the page in `{#key}` in the layout so a new URL means a new component:[^state]

```svelte title="src/routes/posts/+layout.svelte"
<script lang="ts">
  import { page } from "$app/state";
  let { children } = $props();
</script>

{#key page.url.pathname}
  {@render children()}
{/key}
```

With that in place, `/posts/a` to `/posts/b` logged `SLUG PAGE destroyed` and `SLUG PAGE mounted`, `liked` went back to false, and the layout's filter panel stayed open, since the key only wraps the page.

I'd rather keep the reuse and derive what depends on `data`; a remount throws away the DOM and any focus or scroll inside it.

**Quiz:** A /products/[id] page has let qty = $state(1). You set qty to 4 on /products/7, then follow a link to /products/9. What does the quantity field show?

- 1, because a new product page starts fresh
- 4
- Whatever the load function returns for product 9

**Answer:** 4 — The component is reused, so its $state keeps its value. Wrap the page in {#key page.url.pathname} in a layout if it should reset.

- Not "1, because a new product page starts fresh": Both URLs use the same +page.svelte, so SvelteKit keeps the mounted component and only changes data. The script doesn't run again.
- Not "Whatever the load function returns for product 9": Only if qty is derived from data. A $state initialised from data reads it once.

## Data flows down

A layout can have its own `load` in `+layout.ts`, and its return value goes to the layout and to every page under it.

I had the posts layout return `{ a: 1, b: 2 }` and the post page return `{ b: 3, c: 4, title }`. The page's `data` came out as `{ a: 1, b: 3, c: 4, title: "Post a" }`, the merge the docs describe: "the last one 'wins'".[^load] The layout's own `data` prop still said `b: 2`, because it only gets its own load and the ones above it.

The layout's `load` didn't run again on navigation. Going from `/posts/a` to `/posts/b` logged one page load and no layout load, and a counter the layout returned stayed at 1. SvelteKit tracks what each `load` reads, so a function that never touches `params` has no reason to re-run when they change.[^load]

Then I added one line, `void params.slug`, to the layout's load, and the same click logged both loads and bumped the counter to 2. A layout load that reads the slug runs once per post, which costs nothing here and could be a database call in your app.

Both files are universal loads (`.ts`, not `.server.ts`), so they run on the server for the first request and in the browser after that.[^routing]

On a full page load of `/posts/a`, I saw them logged once in the dev server's terminal and once more in the browser console during hydration. Rename the file to `+page.server.ts` when the data needs a secret or a database; that's the next part's territory.

**Quiz:** +layout.ts returns { user: 'ada', theme: 'dark' }. The page's +page.ts returns { theme: 'light', post: '…' }. What does the layout component see as data.theme?

- light, because the page's data is merged in
- dark
- A type error, because the keys collide

**Answer:** dark — The layout's data is its own. The page sees theme: 'light', because the last load wins. page.data from $app/state is where a layout can read the merged result.

- Not "light, because the page's data is merged in": The merge goes into the page's data. A layout only receives its own load result and those of layouts above it.
- Not "A type error, because the keys collide": Colliding keys are allowed. The later load wins in the page's data.

## Groups and the `@` reset

Sometimes the URL and the layout disagree. A marketing page and an app dashboard can both sit at the top level, `/pricing` and `/dashboard`, and still want different chrome.

A folder in parentheses is a route group: it can hold a layout, and it doesn't "affect the URL pathname of the routes inside them."[^advanced] With `(app)/dashboard` and `(marketing)/pricing`, `/dashboard` rendered inside the app shell and `/pricing` inside the marketing one.

Groups don't make URLs unique. I added `(app)/pricing` next to `(marketing)/pricing`, and `/pricing` became a 500 with `route_conflict`: "The `/(app)/pricing` and `/(marketing)/pricing` routes conflict with each other."

For one page that needs to skip a layout, put `@` in the file name. `posts/[slug]/print/+page@.svelte` resets to the root layout.[^advanced]

On `/posts/a/print`, the posts layout logged `destroyed` and the root layout's counter still said 2. A segment name after the `@` stops at that ancestor instead: as `+page@posts.svelte`, the print page kept the posts layout again.

I'd use this sparingly. One print view is fine; if half a folder's pages escape its layout, the layout is in the wrong folder.

## React has the same shape

React itself has no router, so the comparison is a framework. Next.js's App Router is the closest: `page.tsx` and `layout.tsx` instead of `+page.svelte` and `+layout.svelte`, a `children` prop for the page, and the same promise that "on navigation, layouts preserve state, remain interactive, and do not rerender."[^next] Route groups even use the same parentheses, and two groups resolving to the same path is an error there too.[^nextgroups]

The differences are in the details. In SvelteKit, a layout's data comes from a `load` next to it and arrives as a prop to the layout and the pages below; in the App Router, a layout is a Server Component by default and fetches its own data. SvelteKit has the `@` reset for one-off escapes, and the Next.js docs point to route groups for opting segments out of a layout.

If you've used one, you can read the other's file tree on day one.

That's the case I'd make for SvelteKit here: you get the same model as the biggest React framework, and every file in it is a Svelte component with the runes from parts 3 to 7. The like button that stayed liked is the same lesson as a prop you copied into a `let`, just one level up.

## What I'd take from this

The file tree under `src/routes` is a component tree, and SvelteKit keeps as much of it mounted as it can.

Layouts survive navigation inside their folder. A page survives navigation to another URL of the same route, with new `data` and old local state.

Write pages so they don't care: derive from `data`, keep state you want to persist in a layout, and reach for `{#key}` only when a page really has to start over.

The [routing](https://svelte.dev/docs/kit/routing) and [advanced routing](https://svelte.dev/docs/kit/advanced-routing) pages cover every file this post used, and the [state management](https://svelte.dev/docs/kit/state-management) page has the component-reuse warning with the fixes.

Next: form actions, and what a `+page.server.ts` can do besides load.

[^routing]: SvelteKit docs, [Routing](https://svelte.dev/docs/kit/routing).

[^advanced]: SvelteKit docs, [Advanced routing](https://svelte.dev/docs/kit/advanced-routing): sorting, route groups, and `+page@`.

[^kit3]: SvelteKit docs, [Migrating to SvelteKit 3](https://svelte.dev/docs/kit/migrating-to-sveltekit-3).

[^state]: SvelteKit docs, [State management: component and page state is preserved](https://svelte.dev/docs/kit/state-management).

[^load]: SvelteKit docs, [Loading data](https://svelte.dev/docs/kit/load).

[^next]: Next.js docs, [Layouts and pages](https://nextjs.org/docs/app/getting-started/layouts-and-pages).

[^nextgroups]: Next.js docs, [Route groups](https://nextjs.org/docs/app/api-reference/file-conventions/route-groups).

- **Part 13 — Form actions and progressive enhancement**: A form that posts to +page.server.ts with JavaScript off, what use:enhance changes once it's on, and the redirect that stops a reload from submitting twice
