v5.2 additions worth knowing about:
  • defineRoutes() — type-safe routes + nav/paths helpers (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 reactive hasPermission() by default (Permissions)
  • onRevalidationFailure config — custom handling for revalidation failures (Permissions)
  • relativeLocation field on every Router event payload (see callbacks-events)

🧭 Navigation Functions

Programmatic navigation between routes

Demo
FunctionParametersReturnsDescription
push()location: string | array | object
param2?: any
param3?: Record<string, any>
param4?: any
Promise<void>Navigate to new route, adding to browser history
replace()location: string | array | object
param2?: any
param3?: 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-voidRe-run guards and conditions against the currently mounted route without remounting. Coalesces calls within ~50ms.
Controls
Navigation Functions
 
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
FunctionReturnsDescription
location()stringGet current location path (e.g., '/about')
querystring()stringGet raw query string without '?' (e.g., 'foo=bar')
query()
query<T>()
Record<string, string | string[]>
T
Get parsed querystring as object. Optional generic type for intellisense
routeParams()
routeParams<T>()
Record<string, string> | undefined
T | undefined
Get current route parameters from URL pattern. Optional generic type for intellisense
navigationContext()
navigationContext<T>()
any | null
T | null
Get navigation context data passed during navigation. Optional generic type for intellisense
loc()LocationGet full location object with path and querystring
Controls
State Accessors
 
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
FunctionParametersDescription
setHashRoutingEnabled()value: booleanEnable hash mode (true) or history mode (false). Default: true
setBasePath()value: stringSet base path for history mode (e.g., '/app')
setParamReplacementPlaceholder()value: stringSet 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
Router Configuration
 
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
FunctionParametersDescription
wrap()options: WrapOptionsWrap component with async loading, conditions, props, and loading state
WrapOptions Interface
PropertyTypeDescription
componentComponent | AsyncComponentSvelte component or async loader function
conditionsFunction[]Route guard conditions (must all return true)
propsRecord<string, any>Static props to pass to component
routeContextanyCustom metadata for the route
loadingComponentComponentComponent to show while loading async route
shouldDisplayLoadingOnRouteLoadbooleanWait for component data before hiding loading
Controls
Route Wrapping
 
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
FunctionParametersDescription
defineRoutes() v5.2.0definitions: 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: stringRegister a single named route
getRoutes()-Get all registered named routes
getRouteByName()name: stringGet the pattern for a registered route (or undefined)
hasRoute()name: stringCheck if a route name is registered
buildUrl()name: string
params?: 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
Named Routes
 
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
FunctionParametersDescription
configurePermissions()config: PermissionConfigConfigure checkPermissions, unauthorized behavior, optional getCurrentUser override, onRevalidationFailure (v5.2.0)
setCurrentUser() v5.2.0user: anySet 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: ProtectedRouteOptionsCreate wrapped route with permission and authorization checks (no extra wrap() needed)
createProtectedRouteDefinition()options: ProtectedRouteOptionsReturns a route definition for advanced use with wrap()
Controls
Permissions
 
Description
🛡️ Two-Layer Security
  • Role-based: Fast permission checks (any / all)
  • Resource-based: Slow async authorizationCallback for 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
ActionParametersDescription
use:linkhref?: string | array | LinkActionOptionsEnable SPA navigation on anchor tags
use:activeclassName?: stringAdd CSS class to active links. Default: 'active'
Controls
Svelte Actions
 
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
ComponentProps
<Router>routes*: RoutesMap
prefix?: string
zone?: string
restoreScrollState?: boolean
onrouteEvent?: Function
onRouteLoading?: Function
onRouteLoaded?: Function
onConditionsFailed?: Function
onNotFound?: Function
<GlobalErrorHandler>No props - configure via configureGlobalErrorHandler()
* Required props
Controls
Components
 
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.