| | |

Svelte 53 🧡 File-Based Routing System — +page.svelte, +layout.svelte, +error.svelte

⏱️ Estimated read: 8 min | |

SvelteKit operates on a file-system-based router where your directory structure acts as the definitive roadmap for your application’s URLs. By standardizing the naming convention for specific files using the + prefix, the framework removes the need for centralized routing tables or complex boilerplate code. When a user requests a URL, SvelteKit resolves the request by looking for specific files in the corresponding directory, creating a predictable and intuitive environment for building complex applications.

The architecture relies on the interplay between three primary file types: pages, layouts, and error boundaries. Pages provide the primary UI, layouts provide the shell that persists across navigation, and error boundaries provide isolated zones for handling failures. This chapter examines how these components fit together, the hierarchy of nested layouts, and the mechanics of the SvelteKit request lifecycle.

Key point: SvelteKit uses the + prefix to differentiate framework files from standard application components; +page.svelte defines the route content, +layout.svelte defines the shared wrapping UI, and +error.svelte captures and displays failures specific to that subtree of the routing tree.


Why exists

The Routing Overhead Problem. Centralized routing files often grow into unmaintainable lists of thousands of lines of code. This system exists to colocate the route definition with the actual implementation, making the codebase self-documenting.

The Nested UI Problem. Creating persistent components like sidebars or headers across multiple pages usually requires conditional rendering or complex context state. Layout files exist to provide a native, hierarchical way to wrap subsets of pages with persistent UI.

The Fault Tolerance Problem. A single uncaught exception in a client-side app can crash the entire interface. The +error.svelte system exists to provide a granular error boundary, ensuring a failure in one section of the app doesn’t take down the entire user experience.

The Discovery Problem. New developers often struggle to find where a URL logic is implemented. This system exists because the URL path literally matches the file path, reducing the mental overhead of navigating the project.

The State Persistence Problem. Navigating between pages often resets state unnecessarily. This system exists to preserve parent layout state, meaning elements like timers or sidebars remain active while only the inner +page.svelte changes during navigation.


a. The +page.svelte route definition

The +page.svelte file is the fundamental building block of a route. It is the component rendered when a user navigates to the path corresponding to its directory. Every directory in src/routes that contains a +page.svelte is automatically converted into a routable URL.

<!-- src/routes/profile/+page.svelte -->
<h1>User Profile</h1>
<p>Welcome to your dashboard.</p>

This component is the end-point for navigation. It receives data from the load function (defined in +page.server.ts or +page.ts) via the data prop. The framework ensures this component is rendered on the server for initial requests and then updated on the client during SPA-style navigation.


b. The +layout.svelte shell

Layouts are used to share UI components such as navigation menus, footers, or authentication headers across multiple routes. A +layout.svelte applies to the current directory and all subdirectories, allowing for nested layouts.

<!-- src/routes/+layout.svelte -->
<nav>
  <a href="/">Home</a>
</nav>

<slot /> <!-- Child pages render here -->

When you define a layout in src/routes, it wraps every route in your application. If you define a layout in src/routes/blog/+layout.svelte, it only wraps the pages under the /blog directory. The <slot /> element is mandatory; it defines the anchor point where the child layout or page content will be injected.


c. The +error.svelte boundary

The +error.svelte file is a special error boundary. When an error is thrown inside a load function or occurs during the rendering of a page, SvelteKit searches for the nearest +error.svelte in the directory tree.

<!-- src/routes/+error.svelte -->
<script>
  import { page } from '$app/stores';
</script>

<h1>Error {$page.status}</h1>
<p>{$page.error?.message}</p>

If an error occurs in /blog/my-post, the framework checks /blog/+error.svelte first; if it doesn’t exist, it looks in the parent directories until it reaches the root. This cascading behavior allows you to handle specific 404s or 500s differently depending on the depth of the application structure.


Complete Example Session

// ============================================
// PART 1: THE PAGE
// ============================================
// src/routes/post/+page.svelte
<h1>My Post</h1>

// ============================================
// PART 2: THE LAYOUT
// ============================================
// src/routes/+layout.svelte
<header>Site Header</header>
<slot />

// ============================================
// PART 3: NESTED LAYOUT
// ============================================
// src/routes/blog/+layout.svelte
<aside>Blog Categories</aside>
<slot />

// ============================================
// PART 4: ERROR BOUNDARY
// ============================================
// src/routes/+error.svelte
<p>Something broke!</p>

// ============================================
// PART 5: DATA PASSING
// ============================================
// src/routes/post/+page.server.ts
export const load = () => ({ title: "Hello" });

// ============================================
// PART 6: CONSUMING DATA
// ============================================
// src/routes/post/+page.svelte
export let data;
<h1>{data.title}</h1>

// ============================================
// PART 7: ERROR TRIGGER
// ============================================
// src/routes/post/+page.server.ts
import { error } from '@sveltejs/kit';
// throw error(404, 'Not found');

// ============================================
// PART 8: ROUTE GROUP
// ============================================
// src/routes/(app)/dashboard/+page.svelte
// (group) does not affect URL path

// ============================================
// PART 9: THE ROOT LAYOUT
// ============================================
// src/routes/+layout.svelte
// This wraps every single page in the app.

// ============================================
// PART 10: LAYOUT DATA
// ============================================
// src/routes/+layout.server.ts
export const load = () => ({ user: "Guest" });

These parts show the hierarchy of components, how layouts nest, and how errors propagate through the file tree.


Quick Reference

File Roles

FileScopePrimary Duty
+page.svelteRouteUI rendering
+layout.svelteSubtreeShared structure
+error.svelteSubtreeCatch failures

Hierarchy Rules

FeatureBehavior
NestingLayouts wrap child content
FallbackErrors bubble up to parents
DataLayouts pass data to children

Slot Logic

ElementDescription
<slot />Injection point for nested content

Best Practices

✅ Do This:

// Use layouts for shared headers and navs
<nav>...</nav> <slot />                                       // ✅

// Define specific error messages
<h1>{$page.status}</h1>                                       // ✅

// Nest layouts for partial shared UI
src/routes/blog/+layout.svelte                                // ✅

// Use $page store for error details
import { page } from '$app/stores';                             // ✅

❌ Don’t Do This:

// Don't put logic in +layout.svelte if unnecessary
// Keep it in +layout.server.ts                               // ❌

// Don't forget the <slot /> tag
// Page will fail to render                                   // ❌

// Don't mix routing files with components
// Use src/lib/components for generic UI                      // ❌

// Don't swallow errors in the error boundary
// Always log the error to a service                          // ❌

Common Pitfalls

PitfallWhy It HappensFix
Missing slotForgot <slot />Add it to layout
Layout resetNavigating within layoutSvelteKit preserves it
Wrong errorBubbled too highCreate local +error.svelte
Route conflictOverlapping path namesUse route groups

Real-World Examples

1. Simple layout

<main><slot /></main>

2. Root error boundary

<h1>500 - Server Error</h1>

3. Page with data

<script>export let data;</script>
<h1>{data.title}</h1>

4. Nested layout

<aside>Menu</aside><slot />

5. Custom error page

<p>Page {page.url.pathname} not found</p>

6. Route group

src/routes/(auth)/login/+page.svelte

7. Layout data

export const load = () => ({ theme: 'dark' });

8. Layout data consumer

<div class={data.theme}>...</div>

9. Error bubbling

/blog/post/+error.svelte (local)
/blog/+error.svelte (fallback)

10. Data prop

export let data;

Visual

Layout Nesting Hierarchy

┌──────────────────────────────────────┐
│  Root +layout.svelte                 │
│  ┌─────────────────────────────────┐ │
│  │  Blog +layout.svelte            │ │
│  │  ┌───────────────────────────┐  │ │
│  │  │  +page.svelte             │  │ │
│  │  └───────────────────────────┘  │ │
│  └─────────────────────────────────┘ │
└──────────────────────────────────────┘

Error Propagation

┌──────────────────────────────────────┐
│  /blog/post/ throws error            │
│       │                              │
│       ▼                              │
│  Look for /blog/post/+error.svelte   │
│       │                              │
│       ▼ (if missing)                 │
│  Look for /blog/+error.svelte        │
│       │                              │
│       ▼ (if missing)                 │
│  Look for /+error.svelte             │
└──────────────────────────────────────┘

The Route Component Tree

┌──────────────────────────────────────┐
│  [Layout]                            │
│    [Layout]                          │
│      [Page]                          │
│        [Component]                   │
└──────────────────────────────────────┘

Summary

ItemValue
UI Definition+page.svelte
Shared UI+layout.svelte
Error Handling+error.svelte
Injection<slot />
NestingHierarchical
BubblingCascading errors

Key takeaways:

  • Naming is everything. Files prefixed with + are special and control the framework behavior, while other files are treated as components.
  • Layouts are wrappers. The <slot /> element is the mandatory point where child components are injected into the parent layout.
  • Errors are scoped. You can provide a specific error page for a subdirectory to ensure the user gets context-aware feedback.
  • Data flows downwards. Parent layout data is accessible to all child components within the layout tree, simplifying global state management.
  • Route groups allow organization. Parentheses (name) let you group routes logically without impacting the actual URL path.

Remember: The file-based routing system is designed to match your application’s physical structure with its logical URL path. By utilizing +page, +layout, and +error files, you define a clear, maintainable hierarchy where shared UI and fault-handling are automatically handled by the framework’s file-system resolver.

Was this helpful?


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!