Understanding SvelteKit Routing
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!