Svelte 46: A Lightweight Client-Side Router Pattern
easy⏱ 5 mincoursesvelte
A store as the single source of truth for navigation
Everything else follows from one decision: represent 'the current screen' as a store value instead of scattering boolean flags across components. Any component can read $currentRoute to decide what to show, and any component can call navigate() to change it — no parent/child relationship required between the nav and the content it controls.
// router.js
export const currentRoute = writable('home');
export function navigate(route) {
currentRoute.set(route);
}
// App.svelte
{#if $currentRoute === 'home'}
<Home />
{:else if $currentRoute === 'about'}
<About />
{/if}
This is real SvelteKit's mental model, not a toy
SvelteKit — Svelte's official meta-framework — layers file-based routes, load functions, server-side rendering, and code-splitting on top of this exact idea, none of which can run inside this single-file browser sandbox (there's no filesystem, no server, no bundler here). But conceptually, navigating in SvelteKit still boils down to 'update a piece of state describing the current route, and let the UI react to it' — you've just built the reactive core of it by hand.
Navigate around
Click through Home, About, and Contact. Notice the active nav button restyles itself based on the SAME $currentRoute value that decides which page renders — one store, two consumers agreeing perfectly.