defineRoutes()— type-safe routes +nav/pathshelpers (see Named Routes and the dedicated feature page)revalidateCurrentRoute()— re-check the active route on out-of-band permission changes (Navigation Functions)setCurrentUser()/getCurrentUser()— module-level state for reactivehasPermission()by default (Permissions)onRevalidationFailureconfig — custom handling for revalidation failures (Permissions)relativeLocationfield on every Router event payload (see callbacks-events)
🧭 Navigation Functions
Programmatic navigation between routes
Demo
| Function | Parameters | Returns | Description |
|---|---|---|---|
push() | location: string | array | objectparam2?: anyparam3?: Record<string, any>param4?: any | Promise<void> | Navigate to new route, adding to browser history |
replace() | location: string | array | objectparam2?: anyparam3?: Record<string, any>param4?: any | Promise<void> | Replace current route without adding to history |
pop() | - | Promise<void> | Navigate back in history (browser back button) |
goBack() | - | Promise<void> | Navigate to referrer with automatic scroll restoration |
revalidateCurrentRoute() v5.2.0 | - | void | Re-run guards and conditions against the currently mounted route without remounting. Coalesces calls within ~50ms. |
Controls
Description
📍 Multiple Formats
All navigation functions support multiple calling formats: string, array, object, and multi-parameter.
🔄 History Management
- push(): Adds to browser history (user can go back)
- replace(): Replaces current entry (no back navigation)
- pop(): Browser back button equivalent
- goBack(): Navigate to referrer with automatic scroll restoration (requires referrer tracking enabled)
🎯 Navigation Context
Pass data between routes without showing it in URL using the navigationContext parameter.
📊 State Accessor Functions
Access current routing state
Demo
| Function | Returns | Description |
|---|---|---|
location() | string | Get current location path (e.g., '/about') |
querystring() | string | Get raw query string without '?' (e.g., 'foo=bar') |
query() | Record<string, string | string[]> | Get parsed querystring as object. Optional generic type for intellisense |
routeParams() | Record<string, string> | undefined | Get current route parameters from URL pattern. Optional generic type for intellisense |
navigationContext() | any | null | Get navigation context data passed during navigation. Optional generic type for intellisense |
loc() | Location | Get full location object with path and querystring |
Controls
Description
⚡ Reactive State
All accessor functions return current values and work with Svelte's $derived for reactivity.
🔤 TypeScript Support
Use generic type parameters for type-safe route parameters and navigation context.
📦 Location Object
The loc() function returns both location and querystring in one call.
⚙️ Configuration Functions
Configure router behavior (must be called before app mount)
Demo
| Function | Parameters | Description |
|---|---|---|
setHashRoutingEnabled() | value: boolean | Enable hash mode (true) or history mode (false). Default: true |
setBasePath() | value: string | Set base path for history mode (e.g., '/app') |
setParamReplacementPlaceholder() | value: string | Set placeholder for missing route parameters. Default: 'N-A' |
getHashRoutingEnabled() | - | Get current routing mode (hash or history) |
getBasePath() | - | Get current base path setting |
getParamReplacementPlaceholder() | - | Get current parameter placeholder value |
Controls
Description
🔀 Routing Modes
- Hash mode: URLs like
#/about(default, no server config needed) - History mode: Clean URLs like
/about(requires server fallback)
📍 Base Path
Use when app is hosted in a subdirectory (e.g., example.com/my-app/about).
⚠️ Timing
All configuration functions must be called before mounting your Svelte app.
📦 Route Wrapping
Wrap routes with async loading, conditions, and metadata
Demo
| Function | Parameters | Description |
|---|---|---|
wrap() | options: WrapOptions | Wrap component with async loading, conditions, props, and loading state |
WrapOptions Interface
| Property | Type | Description |
|---|---|---|
component | Component | AsyncComponent | Svelte component or async loader function |
conditions | Function[] | Route guard conditions (must all return true) |
props | Record<string, any> | Static props to pass to component |
routeContext | any | Custom metadata for the route |
loadingComponent | Component | Component to show while loading async route |
shouldDisplayLoadingOnRouteLoad | boolean | Wait for component data before hiding loading |
Controls
Description
🔄 Async Loading
Use dynamic imports for code splitting. Show loading component while route loads.
🛡️ Route Guards
Add conditions that must pass before showing route. Perfect for authentication checks.
📊 Route Metadata
Attach custom data like breadcrumbs, page titles, or permissions to routes.
🏷️ Named Routes
Register and resolve routes by name
Demo
| Function | Parameters | Description |
|---|---|---|
defineRoutes() v5.2.0 | definitions: Record<string, RouteDefinition> | Type-safe routes — returns { routes, nav, paths } with full IDE autocomplete. Auto-calls registerRoutes(). |
registerRoutes() | routes: Record<string, string> | Register named routes for programmatic navigation |
registerRoute() | name: string, pattern: string | Register a single named route |
getRoutes() | - | Get all registered named routes |
getRouteByName() | name: string | Get the pattern for a registered route (or undefined) |
hasRoute() | name: string | Check if a route name is registered |
buildUrl() | name: stringparams?: Record<string, any>query?: Record<string, any> | Build URL string from a named route + params + optional query |
clearRoutes() | - | Clear all registered routes (mostly for tests) |
Controls
Description
📛 Why Named Routes?
Change URL patterns without updating navigation calls throughout your app.
🔗 Type Safety
defineRoutes() (v5.2.0+) extracts :param names from path
patterns at the type level. Typos in route names or parameter names fail at compile
time. Dedicated guide →
⚡ URL Building
Build URLs at runtime with buildUrl() or the typed paths.X() helpers from defineRoutes().
🔐 Permissions & Authorization
Role-based and resource-based access control
Demo
| Function | Parameters | Description |
|---|---|---|
configurePermissions() | config: PermissionConfig | Configure checkPermissions, unauthorized behavior, optional getCurrentUser override, onRevalidationFailure (v5.2.0) |
setCurrentUser() v5.2.0 | user: any | Set the current user. Drives the default reactive currentUserGetter — every hasPermission() in a reactive context re-evaluates. |
getCurrentUser() v5.2.0 | - | Read the current user. Symmetric reader for the setCurrentUser-backed state. |
hasPermission() | requirements: { any?: string[]; all?: string[] } | Check if user satisfies the requirements. Reactive when called in $derived / {#if} / $effect. |
createProtectedRoute() | options: ProtectedRouteOptions | Create wrapped route with permission and authorization checks (no extra wrap() needed) |
createProtectedRouteDefinition() | options: ProtectedRouteOptions | Returns a route definition for advanced use with wrap() |
Controls
Description
🛡️ Two-Layer Security
- Role-based: Fast permission checks (
any/all) - Resource-based: Slow async
authorizationCallbackfor specific resources
⚡ Reactive by default (v5.2.0)
The default currentUserGetter is backed by module-level $state.
Calling setCurrentUser() triggers every hasPermission() in a
reactive context to re-evaluate. No subscription wiring needed.
🔄 Active-route revalidation
hasPermission() covers UI element visibility. revalidateCurrentRoute() covers "user is sitting on a now-forbidden page". Use both for full coverage.
🎯 Permission requirements
Pass { any: [...] } for OR logic or { all: [...] } for AND logic.
🎬 Svelte Actions
Declarative routing and active link highlighting
Demo
| Action | Parameters | Description |
|---|---|---|
use:link | href?: string | array | LinkActionOptions | Enable SPA navigation on anchor tags |
use:active | className?: string | Add CSS class to active links. Default: 'active' |
Controls
Description
🔗 Link Action
Prevents full page reload, enables SPA navigation. Works with modifier keys (Ctrl+Click) in history mode.
✨ Active Action
Automatically adds CSS class when link matches current route. Perfect for nav menus.
🎨 Styling
Customize the active class name to match your CSS framework or design system.
🧩 Components
Main router and error handling components
Demo
| Component | Props |
|---|---|
<Router> | routes*: RoutesMapprefix?: stringzone?: stringrestoreScrollState?: booleanonrouteEvent?: FunctiononRouteLoading?: FunctiononRouteLoaded?: FunctiononConditionsFailed?: FunctiononNotFound?: Function |
<GlobalErrorHandler> | No props - configure via configureGlobalErrorHandler() |
Controls
Description
🎯 Router Component
Main component that renders the current route. Supports nested routers via prefix and multi-zone routing via zone.
🚨 Error Handler
Catches all unhandled errors. Configure recovery strategies with configureGlobalErrorHandler().
📜 Scroll Restoration
Enable restoreScrollState to save/restore scroll positions on navigation.