← Back to all posts

Understanding SvelteKit Routing

By Mark •
sveltekitroutingtutorial

Understanding SvelteKit Routing

SvelteKit's routing system is powerful and intuitive. Let's explore how it works!

File-Based Routing

In SvelteKit, the file structure in your src/routes directory determines your app's routes:

src/routes/
ā”œā”€ā”€ +page.svelte           → /
ā”œā”€ā”€ about/
│   └── +page.svelte       → /about
└── blog/
    ā”œā”€ā”€ +page.svelte       → /blog
    └── [slug]/
        └── +page.svelte   → /blog/:slug

Special Files

SvelteKit uses a naming convention with + prefix:

+page.svelte

The actual page component (like page.tsx in Next.js).

+page.ts or +page.server.ts

Data loading functions that run before the page renders.

+layout.svelte

Wraps pages with shared UI (navigation, footer, etc.)

+error.svelte

Error boundaries for handling exceptions.

Dynamic Routes

Dynamic routes use square brackets [param]:

routes/
└── blog/
    └── [slug]/
        ā”œā”€ā”€ +page.ts       # Load post data
        └── +page.svelte   # Display post

Access the parameter in your load function:

export async function load({ params }) {
  const { slug } = params;
  // Fetch data based on slug
  return { post };
}

Layout Hierarchy

Layouts can be nested! Each +layout.svelte wraps all child routes:

routes/
ā”œā”€ā”€ +layout.svelte         # Wraps everything
└── blog/
    ā”œā”€ā”€ +layout.svelte     # Wraps only /blog/* routes
    └── +page.svelte

Conclusion

SvelteKit's routing is elegant and powerful. Once you understand the conventions, building complex applications becomes a breeze!