### Run Example Application
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/README.md
Navigate to an example directory, install dependencies, and start the development server.
```bash
cd example-history
npm install
npm run dev
```
--------------------------------
### Example App Setup for E2E
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/e2e/README.md
Instructions to ensure the example app's dependencies are installed, which is a prerequisite for running E2E tests.
```bash
cd example && npm install
```
--------------------------------
### Run Example App
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/HIERARCHICAL_ROUTES_EXAMPLE.md
Commands to start the development server for the example application.
```bash
# From project root
make dev
# or
cd example && npm run dev
```
--------------------------------
### Run History Mode Example
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/CLAUDE.md
Start a development server for the history mode example, which uses clean URLs. Ensure you have the necessary build tools installed.
```bash
make dev
```
--------------------------------
### Run Development Server (Hash Mode)
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/DEVELOPMENT.md
Starts the hash mode example with traditional URLs.
```bash
make dev-hash
```
--------------------------------
### Install Dependencies
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/DEVELOPMENT.md
Installs project dependencies. Can be used interchangeably with `make setup`.
```bash
make install
# or
make setup
```
--------------------------------
### Run Development Server (History Mode)
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/DEVELOPMENT.md
Starts the history mode example with clean URLs. Recommended for testing new features.
```bash
make dev
```
--------------------------------
### Build Both Examples
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/DEVELOPMENT.md
Compiles both the hash and history mode examples.
```bash
make build
```
--------------------------------
### Build Both Example Apps
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/CLAUDE.md
Compile both the history mode and hash mode example applications. This command is useful for generating production-ready builds of the examples.
```bash
make build-examples
```
--------------------------------
### Build History Mode Example Only
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/DEVELOPMENT.md
Compiles only the history mode example.
```bash
make build-history
```
--------------------------------
### Testing Examples
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/CONTEXT.md
Paths to example applications demonstrating different features.
```APIDOC
## Testing Examples
### Description
Paths to example applications showcasing various features of the router.
### Examples:
- `example/`: Basic hash mode example.
- `example-history/`: History mode example with querystring and filter demos.
- `/querystring-demo`: Interactive querystring demo with array format switching.
- `/filters-demo`: Filter system demo with product filtering.
- `/route-data-demo`: Route data extraction examples.
- `example-permissions/`: Example demonstrating the permission system.
```
--------------------------------
### Svelte 4 Router Setup
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/MIGRATION.md
Example of setting up svelte-spa-router in Svelte 4. Ensure correct import paths and reactivity declarations.
```svelte
{#if isHomePage}
Welcome Home!
{/if}
console.log(e.detail)}
/>
```
--------------------------------
### Build Hash Mode Example Only
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/DEVELOPMENT.md
Compiles only the hash mode example.
```bash
make build-hash
```
--------------------------------
### Complete Example: Combining Hierarchical and Flat Routes
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/CLAUDE.md
Demonstrates a comprehensive example of defining both hierarchical and flat routes, then combining them. It also shows how to navigate using route names with the push function.
```javascript
import { createHierarchy } from '@keenmate/svelte-spa-router/helpers/hierarchy'
import { push } from '@keenmate/svelte-spa-router'
// Tree structure
const hierarchicalRoutes = createHierarchy({
'/admin': {
name: 'admin',
component: AdminLayout,
breadcrumbs: [{ label: 'Admin' }],
permissions: { any: ['admin'] },
children: {
'users': {
name: 'adminUsers',
component: AdminUsers,
breadcrumbs: [{ label: 'Users' }],
children: {
':id': {
name: 'adminUserDetail',
component: AdminUserDetail,
breadcrumbs: [{ label: 'User Detail' }],
authorizationCallback: async (detail) => {
return await checkUserAccess(detail.routeParams.id)
},
children: {
'permissions': {
// No name - accessed via tabs/UI only
component: UserPermissions,
breadcrumbs: [{ label: 'Permissions' }]
},
'activity': {
component: UserActivity,
breadcrumbs: [{ label: 'Activity' }]
}
}
}
}
}
}
}
})
// Flat routes
const flatRoutes = {
'/': Home,
'/about': About
}
// Combine both
const routes = {
...hierarchicalRoutes,
...flatRoutes
}
// Navigate using names
await push('adminUserDetail', { id: 123 })
// Results in: /admin/users/123
```
--------------------------------
### Development Commands
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/CONTEXT.md
Common development commands for building, running examples, and linting the project.
```bash
make dev # Run history mode example (port 5050)
make dev-hash # Run hash mode example
make build # Build both examples
make lint # Run ESLint
```
--------------------------------
### Install and Run E2E Tests
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/e2e/README.md
Commands to install dependencies, set up Playwright, and run the end-to-end tests in various modes (headless, UI, headed).
```bash
npm install # root deps (includes @playwright/test)
npm run test:e2e:install # one-time: download chromium binary
npm run test:e2e # headless run
npm run test:e2e:ui # Playwright Test UI
npm run test:e2e:headed # watch the browser
```
--------------------------------
### Development Commands
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/CONTEXT.md
Commands for running and building the examples.
```APIDOC
## Development Commands
### Description
Commands to build, run, and lint the project examples.
### Commands:
- `make dev`: Run history mode example (port 5050).
- `make dev-hash`: Run hash mode example.
- `make build`: Build both examples.
- `make lint`: Run ESLint.
```
--------------------------------
### Svelte 5 Router Setup
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/MIGRATION.md
Example of setting up svelte-spa-router in Svelte 5. Note the updated import paths and the use of $props() and $derived() for reactivity.
```svelte
{#if isHomePage}
Welcome Home!
{/if}
console.log(e.detail)}
/>
```
--------------------------------
### Complete Hierarchical Route Example
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/ai/tree-structure.txt
A comprehensive example demonstrating nested routes with inheritance of breadcrumbs, permissions, and authorization callbacks, alongside named routes.
```javascript
import { createHierarchy } from '@keenmate/svelte-spa-router/helpers/hierarchy'
import { setHierarchicalRoutesEnabled } from '@keenmate/svelte-spa-router'
// Enable hierarchical mode for inheritance
setHierarchicalRoutesEnabled(true)
const hierarchicalRoutes = createHierarchy({
'/admin': {
name: 'admin',
component: AdminLayout,
breadcrumbs: [{ label: 'Admin' }],
permissions: { any: ['admin'] },
children: {
'users': {
name: 'adminUsers',
component: AdminUsers,
breadcrumbs: [{ label: 'Users' }],
permissions: { any: ['users.view'] },
children: {
':id': {
name: 'adminUserDetail',
component: UserDetail,
breadcrumbs: [{ label: 'User Detail' }],
authorizationCallback: async (detail) => {
return await canViewUser(detail.routeParams.id)
},
children: {
'permissions': {
component: UserPermissions,
breadcrumbs: [{ label: 'Permissions' }],
permissions: { any: ['users.permissions.edit'] }
},
'activity': {
component: UserActivity,
breadcrumbs: [{ label: 'Activity' }]
}
}
}
}
},
'settings': {
name: 'adminSettings',
component: AdminSettings,
breadcrumbs: [{ label: 'Settings' }]
}
}
}
})
```
--------------------------------
### Make Commands for E2E Tests
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/e2e/README.md
Alternative commands using 'make' to install and run end-to-end tests.
```bash
make test-e2e
make test-e2e-install
make test-e2e-ui
```
--------------------------------
### Dockerfile for History Mode
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/example/README.md
Example Dockerfile snippet to build an image for history mode routing.
```dockerfile
# For history mode
ARG ROUTING_MODE=history
ENV VITE_ROUTING_MODE=$ROUTING_MODE
RUN npm run build:${ROUTING_MODE}
```
--------------------------------
### Adding a New E2E Fixture
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/e2e/README.md
Step-by-step guide for adding a new fixture page and corresponding spec file for end-to-end testing.
```markdown
1. Create `example/src/routes/test/Test.svelte` — minimal page, only
the props/config the spec needs, state via `data-testid`.
2. Register the route(s) in `example/src/App.svelte` just before `'*': NotFound`.
3. Add a row to `example/src/routes/test/TestIndex.svelte` so the fixture is
discoverable in the browser at `/test`.
4. Write `e2e/.spec.ts`. Start the docstring with a short summary of
what the fixture exposes (testids + buttons).
5. Run `npm run test:e2e` until green.
6. Flip the row in the coverage table above from ❌ to 🟡 or ✅.
```
--------------------------------
### Array Format Configuration Examples
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/docs/querystring-filters.md
Demonstrates how to configure querystring helpers to handle array formats. Supports auto-detection, explicit repeat, or explicit comma formats.
```javascript
// Auto-detect (default) - handles both formats
// ?tags=foo&tags=bar → { tags: ['foo', 'bar'] }
// ?tags=foo,bar,baz → { tags: ['foo', 'bar', 'baz'] }
// Explicit repeat format
configureQuerystring({ arrayFormat: 'repeat' })
// ?tags=foo&tags=bar
// Explicit comma format
configureQuerystring({ arrayFormat: 'comma' })
// ?tags=foo,bar,baz
```
--------------------------------
### Run Development Server (Hash Mode)
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/example/README.md
Starts the development server using hash-based routing for URLs like `/#/about`. Runs on http://localhost:5051.
```bash
npm run dev:hash
```
--------------------------------
### Install svelte-spa-router
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/README.md
Install the package using npm. Ensure Node.js 22 or higher is used for production builds due to compatibility issues with Svelte 5 in Node.js 20.
```sh
npm install @keenmate/svelte-spa-router
```
--------------------------------
### Log Configuration Errors
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/ai/debug-logging.txt
Use console.warn and console.error for setup and configuration issues. These messages are always visible and not controlled by the log level.
```javascript
console.warn('Missing permission handler')
console.error('Invalid route configuration')
```
--------------------------------
### Wrapping Routes with Authentication Check
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/ai/error-handling.txt
This example uses the `wrap` utility to protect a route, throwing an error if authentication fails. This error will be caught by the GlobalErrorHandler.
```javascript
import { wrap } from '@keenmate/svelte-spa-router/wrap'
const routes = {
'/protected': wrap({
asyncComponent: () => import('./Protected.svelte'),
conditions: [
async (detail) => {
const valid = await checkAuth()
if (!valid) {
throw new Error('Unauthorized access')
}
return true
}
]
})
}
```
--------------------------------
### Custom Go Back Navigation Logic
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/docs/navigation.md
Handle custom logic before navigating back, such as confirming unsaved changes. This example shows how to manually construct the URL from the referrer and use `push()`, noting that manual pushes do not restore scroll position.
```svelte
```
--------------------------------
### Permission Inheritance Example
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/ai/hierarchical-routes.txt
Use `createProtectedRoute` for routes requiring permissions. Permissions are checked sequentially from parent to child; all must pass.
```javascript
import { createProtectedRoute } from '@keenmate/svelte-spa-router/helpers/permissions'
const routes = {
'/documents': createProtectedRoute({
component: Documents,
permissions: { any: ['read'] }
}),
'/documents/:id': createProtectedRoute({
component: DocumentDetail,
permissions: { any: ['documents.view'] }
// Must have: 'read' AND 'documents.view'
}),
'/documents/:id/edit': createProtectedRoute({
component: DocumentEdit,
permissions: { any: ['documents.edit'] }
// Must have: 'read' AND 'documents.view' AND 'documents.edit'
})
}
```
--------------------------------
### Permission Inheritance Example
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/HIERARCHICAL_ROUTES_DESIGN.md
Illustrates how child routes can inherit parent authorization callbacks, ensuring parent checks are executed before child checks.
```javascript
'/documents/:id': {
authorizationCallback: async (detail) => {
return hasAccess(detail.params.id)
}
},
'/documents/:id/logs': {
authorizationCallback: async (detail) => {
// Parent callback should run first
return hasLogsAccess(detail.params.id)
},
inheritAuthorization: true // Parent auth runs first
}
```
--------------------------------
### Condition Inheritance Example
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/ai/hierarchical-routes.txt
Wrap routes with `wrap` to define conditions. Parent conditions execute before child conditions in sequence.
```javascript
import { wrap } from '@keenmate/svelte-spa-router/wrap'
const routes = {
'/admin': wrap({
component: AdminLayout,
conditions: [
async () => await isAuthenticated()
]
}),
'/admin/users': wrap({
component: AdminUsers,
conditions: [
async () => await hasAdminRole()
]
// Runs: isAuthenticated → hasAdminRole
}),
'/admin/users/:id': wrap({
component: AdminUserDetail,
conditions: [
async (detail) => {
return await canEditUser(detail.routeParams.id)
}
]
// Runs: isAuthenticated → hasAdminRole → canEditUser
})
}
```
--------------------------------
### Authentication Guard Example
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/ai/guards-conditions.txt
Checks for a valid token in localStorage and redirects to login if not found. Ensures a token is present before proceeding.
```javascript
conditions: [
async () => {
const token = localStorage.getItem('token')
if (!token) {
await push('/login')
return false
}
return await validateToken(token)
}
]
```
--------------------------------
### Resource Ownership Guard Example
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/ai/guards-conditions.txt
Ensures the current user owns the requested resource. Fetches the document and checks ownership, storing the document in `detail.userData` on success.
```javascript
conditions: [
async (detail) => {
const docId = detail.routeParams.id
const doc = await fetchDocument(docId)
if (doc.ownerId !== getCurrentUser().id) {
await push('/not-found')
return false
}
detail.userData.document = doc
return true
}
]
```
--------------------------------
### Hierarchical Route Permission Inheritance Example
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/docs/hierarchical-routes.md
Demonstrates how permissions are checked hierarchically. All ancestor permission checks must pass for access to be granted. If any check fails, access is denied immediately.
```javascript
// Parent requires 'read'
// Child requires 'documents.view'
// Grandchild requires 'logs.view'
// To access /documents/123/logs:
// 1. Check 'read' (parent) → must pass
// 2. Check 'documents.view' (child) → must pass
// 3. Check 'logs.view' (grandchild) → must pass
//
// If ANY check fails, access is denied (fail-fast)
```
--------------------------------
### Example API for Hierarchical Routes
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/HIERARCHICAL_ROUTES_DESIGN.md
Demonstrates how to define hierarchical routes using the `createRoute` function with inheritance flags. Use this API to configure nested routes with inherited breadcrumbs, permissions, and conditions.
```javascript
import { createRoute } from '@keenmate/svelte-spa-router/wrap'
const routes = {
'/documents': createRoute({
component: Documents,
title: 'Documents',
breadcrumbs: [
{ label: 'Home', path: '/' },
{ label: 'Documents' }
],
permissions: { any: ['read'] },
conditions: [requireAuth]
}),
'/documents/:id': createRoute({
component: DocumentDetail,
title: 'Document Detail',
breadcrumbs: [
{ id: 'documentDetail', label: 'Loading...' }
],
permissions: { any: ['documents.view'] },
inheritBreadcrumbs: true, // → Home > Documents > Detail
inheritPermissions: true, // → ['read', 'documents.view']
inheritConditions: true, // → requireAuth + child conditions
authorizationCallback: async (detail) => {
return hasDocumentAccess(detail.params.id)
}
}),
'/documents/:id/logs': createRoute({
component: DocumentLogs,
title: 'Access Logs',
breadcrumbs: [
{ label: 'Access Logs' }
],
permissions: { any: ['logs.view'] },
inheritBreadcrumbs: true, // Full path
inheritPermissions: true, // All permissions
inheritConditions: true, // All parent conditions
inheritAuthorization: true // Parent auth runs first
})
}
```
--------------------------------
### Direct Registration of a beforeLeave Guard
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/ai/navigation-guards.txt
This example demonstrates imperative registration and unregistration of a `beforeLeave` guard using `onMount` and `onDestroy`. It also shows conditional registration using `$effect`.
```svelte
import { registerBeforeLeave, unregisterBeforeLeave, NavigationCancelledError } from '@keenmate/svelte-spa-router/helpers/navigation-guard'
import { onMount, onDestroy } from 'svelte'
let formIsDirty = $state(false)
async function beforeLeave(ctx) {
if (formIsDirty && !confirm('Unsaved changes. Leave anyway?')) {
throw new NavigationCancelledError()
}
}
onMount(() => registerBeforeLeave(beforeLeave))
onDestroy(() => unregisterBeforeLeave(beforeLeave))
// Or with $effect (conditional registration)
$effect(() => {
if (formIsDirty) {
registerBeforeLeave(beforeLeave)
return () => unregisterBeforeLeave(beforeLeave)
}
})
```
--------------------------------
### Router Component with Props
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/ai/basic-setup.txt
Example of passing various properties to the Router component for customization, including prefix, scroll state restoration, and event handlers.
```svelte
console.log(e.detail)} // Route starting
onRouteLoaded={(e) => console.log(e.detail)} // Route loaded
onConditionsFailed={(e) => push('/unauthorized')}
onNotFound={(e) => console.log('404:', e.detail)}
/>
```
--------------------------------
### Authorization Callback Example
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/ai/permissions.txt
Use an authorization callback to perform dynamic checks based on route details. The callback receives a detail object containing route information, querystring, and parameters.
```javascript
authorizationCallback: async (detail) => {
const docId = detail.params.id
// ...
}
```
--------------------------------
### Access Route Parameters in Svelte Component
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/README.md
Access route parameters within a route component using the `$props()` function to get `routeParams`. The `id` parameter is destructured in this example.
```svelte
User ID: {routeParams.id}
```
--------------------------------
### Display All Available Commands
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/DEVELOPMENT.md
Lists all Makefile commands and their descriptions.
```bash
make help
```
--------------------------------
### Static Breadcrumbs Example
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/ai/breadcrumbs.txt
An example of defining static breadcrumbs for a route. The last breadcrumb omits the 'path' property as it represents the current page.
```javascript
breadcrumbs: [
{ label: 'Home', path: '/' },
{ label: 'About' }
]
```
--------------------------------
### Custom Error Component Example
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/ai/error-handling.txt
An example of a custom error component that can be passed to GlobalErrorHandler. It defines slots for error message and action buttons.
```svelte
Oops! {error?.message}
```
--------------------------------
### Check Package Readiness
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/DEVELOPMENT.md
Verifies the package is ready for publishing.
```bash
make check
```
--------------------------------
### Reusable Breadcrumb Component Example
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/ai/breadcrumbs.txt
Create a reusable Svelte component for displaying breadcrumbs. This example uses `routeBreadcrumbs` and the `link` directive for navigation, along with basic styling.
```svelte
```
--------------------------------
### Incorrect routeParams Import
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/MIGRATION.md
Example of an incorrect import statement for routeParams, which should not come from '/stores'.
```javascript
import { routeParams } from '@keenmate/svelte-spa-router/stores'
```
--------------------------------
### Route Wrapping Utility Import
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/MIGRATION.md
Import the wrap utility for route configuration from the '/wrap' path.
```javascript
import { wrap } from '@keenmate/svelte-spa-router/wrap'
```
--------------------------------
### Available Import Paths for svelte-spa-router
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/CLAUDE.md
Lists all valid import paths for the @keenmate/svelte-spa-router library, including the main module, utilities, and specific helper modules. Note that a '/stores' path does not exist.
```text
@keenmate/svelte-spa-router // Main (Router, push, location, etc.)
@keenmate/svelte-spa-router/utils // Alternative for utils
@keenmate/svelte-spa-router/wrap // Route wrapping
@keenmate/svelte-spa-router/active // Active link action
@keenmate/svelte-spa-router/routes // Named routes
@keenmate/svelte-spa-router/helpers/permissions // Permission system
@keenmate/svelte-spa-router/helpers/navigation-guard // Navigation guards
@keenmate/svelte-spa-router/helpers/hierarchy // Hierarchical routes
@keenmate/svelte-spa-router/helpers/error-handler // Error handling
@keenmate/svelte-spa-router/helpers/* // Other helpers
**NO `/stores` path exists - this router uses functions, not stores!**
```
--------------------------------
### Configure Permissions
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/CONTEXT.md
Set up the permission system globally. This function should be called once during application initialization.
```javascript
import { configurePermissions } from "@keenmate/svelte-spa-router/helpers/permissions.svelte.js";
configurePermissions({
// Define roles and their associated permissions
roles: {
admin: { all: ["read", "write"] },
editor: { any: ["read", "publish"] },
viewer: { all: ["read"] }
},
// Optional: Define default permissions if no role matches
// defaultPermissions: { any: ["read"] }
});
```
--------------------------------
### Feature Flag Guard Example
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/ai/guards-conditions.txt
Checks if a specific feature is enabled. Redirects to an alternative route if the feature is disabled.
```javascript
conditions: [
(detail) => {
if (!isFeatureEnabled('newDashboard')) {
push('/old-dashboard')
return false
}
return true
}
]
```
--------------------------------
### Configure Permissions and Set Current User
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/ai/permissions.txt
Configure the permission checking logic and set the initial user state. This should be done before mounting the application.
```javascript
import {
configurePermissions,
setCurrentUser
} from '@keenmate/svelte-spa-router/helpers/permissions'
configurePermissions({
checkPermissions: (user, requirements) => {
if (!user || !requirements) return false
if (requirements.any) return requirements.any.some(p => user.permissions.includes(p))
if (requirements.all) return requirements.all.every(p => user.permissions.includes(p))
return false
}
})
// Push current user into the permission system.
setCurrentUser(null) // logged-out at startup
// After login: setCurrentUser({ id: 42, permissions: ['admin.read'] })
// Websocket update: setCurrentUser({ ...getCurrentUser(), permissions: newPerms })
// Logout: setCurrentUser(null)
```
--------------------------------
### Incorrect routeParams Usage (Svelte 4)
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/MIGRATION.md
Example of incorrect usage of routeParams as a store in Svelte 4 syntax.
```svelte
ID: {$routeParams.id}
```
--------------------------------
### Access Location Parts
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/ai/utilities.txt
Get individual parts of the location, such as the path and querystring, using separate derived stores.
```javascript
import { location, querystring } from '@keenmate/svelte-spa-router'
const path = $derived(location()) // '/user/123'
const query = $derived(querystring()) // 'tab=settings'
const fullUrl = $derived(`${path}?${query}`)
```
--------------------------------
### All Available Import Paths Summary
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/docs/imports.md
A comprehensive list of all available import paths for the svelte-spa-router library, categorized by their functionality.
```javascript
'@keenmate/svelte-spa-router' // Main module (Router, push, location, etc.)
'@keenmate/svelte-spa-router/utils' // Alternative path for utils
'@keenmate/svelte-spa-router/wrap' // Route wrapping
'@keenmate/svelte-spa-router/active' // Active link action
'@keenmate/svelte-spa-router/routes' // Named routes system
'@keenmate/svelte-spa-router/constants' // Constants and enums
'@keenmate/svelte-spa-router/logger' // Debug logging
'@keenmate/svelte-spa-router/helpers/permissions' // Permission system
'@keenmate/svelte-spa-router/helpers/navigation-guard' // Navigation guards
'@keenmate/svelte-spa-router/helpers/hierarchy' // Hierarchical routes
'@keenmate/svelte-spa-router/helpers/error-handler' // Error handling
'@keenmate/svelte-spa-router/helpers/GlobalErrorHandler' // Error component
'@keenmate/svelte-spa-router/helpers/url-helpers' // URL utilities
'@keenmate/svelte-spa-router/helpers/querystring' // Query string helpers
'@keenmate/svelte-spa-router/helpers/route-metadata' // Breadcrumbs/metadata
'@keenmate/svelte-spa-router/helpers/filters' // Filter parsing
```
--------------------------------
### Access Current Raw Querystring
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/ai/utilities.txt
Get the raw querystring from the current URL using the 'querystring' derived store.
```javascript
import { querystring } from '@keenmate/svelte-spa-router'
const qs = $derived(querystring()) // 'tab=settings&page=2'
```
--------------------------------
### Subscription Check Guard Example
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/ai/guards-conditions.txt
Verifies if the user's subscription is active. Redirects to an upgrade page if the subscription is inactive.
```javascript
conditions: [
async (detail) => {
const sub = await fetchSubscription()
if (!sub.isActive) {
await push('/upgrade')
return false
}
return true
}
]
```
--------------------------------
### Role Check Guard Example
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/ai/guards-conditions.txt
Verifies if the current user has the 'admin' role. Redirects to a forbidden page if the role is missing.
```javascript
conditions: [
(detail) => {
const user = getCurrentUser()
if (!user.roles.includes('admin')) {
push('/forbidden')
return false
}
return true
}
]
```
--------------------------------
### Configure Permission System
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/docs/permissions.md
Set up the permission checking logic and the handler for unauthorized access. This is typically done in your main application entry point before mounting the router.
```javascript
import {
configurePermissions,
setCurrentUser
} from '@keenmate/svelte-spa-router/helpers/permissions'
configurePermissions({
checkPermissions: (user, requirements) => {
if (!user) return false
if (!requirements) return true
// Check if user has any of the required permissions
if (requirements.any) {
return requirements.any.some(perm => user.permissions.includes(perm))
}
// Check if user has all required permissions
if (requirements.all) {
return requirements.all.every(perm => user.permissions.includes(perm))
}
return true
},
onUnauthorized: (detail) => {
push('/unauthorized')
}
})
// Push the current user into the permission system. The library keeps an
// internal $state-backed user, so every hasPermission() call site in a
// reactive context (templates, $derived, $effect) re-evaluates automatically
// when you call setCurrentUser() again.
setCurrentUser(null) // logged-out at startup
// Later, on login:
// setCurrentUser({ id: 42, permissions: ['admin.read'] })
// From a websocket permission update:
// setCurrentUser({ ...getCurrentUser(), permissions: newPerms })
// On logout:
// setCurrentUser(null)
```
--------------------------------
### Define Route Patterns with Parameters
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/ai/route-params.txt
Illustrates various ways to define route patterns using single parameters, multiple parameters, wildcards, and named wildcards.
```javascript
'/user/:id' // Single param
'/user/:userId/post/:postId' // Multiple params
'/books/*' // Wildcard (catches /books/anything/here)
'/files/:path*' // Named wildcard (captures rest of path)
```
--------------------------------
### Incorrect params Import
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/MIGRATION.md
Example of an incorrect import statement for parameters, using the old name 'params' instead of 'routeParams'.
```javascript
import { params } from '@keenmate/svelte-spa-router'
```
--------------------------------
### Testing Referrer and goBack()
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/ai/referrer-tracking.txt
This snippet demonstrates how to test navigation flows, check the referrer context, and verify the goBack() function's behavior.
```javascript
// Test navigation flow
await push('/list')
await push('/detail/123')
// Check referrer
const navContext = navigationContext()
expect(navContext.referrer.location).toBe('/list')
// Test goBack
await goBack()
expect(location()).toBe('/list')
```
--------------------------------
### Authorization Callback Inheritance Example
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/ai/hierarchical-routes.txt
Define authorization callbacks within `createProtectedRoute`. Parent callbacks execute before child callbacks.
```javascript
import { createProtectedRoute } from '@keenmate/svelte-spa-router/helpers/permissions'
const routes = {
'/projects/:projectId': createProtectedRoute({
component: ProjectLayout,
permissions: { any: ['projects.view'] },
authorizationCallback: async (detail) => {
return await canAccessProject(detail.routeParams.projectId)
}
}),
'/projects/:projectId/settings': createProtectedRoute({
component: ProjectSettings,
permissions: { any: ['projects.settings'] },
authorizationCallback: async (detail) => {
return await canEditProjectSettings(detail.routeParams.projectId)
}
// Runs: canAccessProject → canEditProjectSettings
})
}
```
--------------------------------
### Run Tests with UI
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/CLAUDE.md
Execute tests and display results in a user interface. This can provide a more interactive testing experience.
```bash
npm run test:ui
```
--------------------------------
### Update Dependencies for @keenmate/svelte-spa-router
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/MIGRATION.md
Use npm to uninstall the old router and install the new one along with Svelte 5.
```bash
npm uninstall svelte-spa-router
npm install @keenmate/svelte-spa-router svelte@^5.0.0
```
--------------------------------
### Route Configuration Imports
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/docs/imports.md
Import utilities for defining routes, wrapping routes with loading or conditions, enabling active link highlighting, and using the named routes system.
```javascript
// Type-safe route definitions (recommended!)
import { defineRoutes } from '@keenmate/svelte-spa-router/routes'
// Wrap routes with loading/conditions
import { wrap } from '@keenmate/svelte-spa-router/wrap'
// Active link highlighting
import active from '@keenmate/svelte-spa-router/active'
// Named routes system
import { registerRoutes, buildUrl } from '@keenmate/svelte-spa-router/routes'
```
--------------------------------
### Route Resolution
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/ai/navigation.txt
The router resolves routes based on whether they start with '/' (exact path) or are treated as named routes.
```javascript
await push('/about') // Exact path
```
```javascript
await push('about') // Named route (if registered)
```
```javascript
await push('userProfile', {}) // Named route with params
```
--------------------------------
### Get Full Location Object
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/ai/utilities.txt
Access the complete location object, including the path and querystring, using the 'loc' function.
```javascript
import { loc } from '@keenmate/svelte-spa-router'
const location = $derived(loc())
// {
// location: '/user/123',
// querystring: 'tab=settings'
// }
```
--------------------------------
### Correct Route Parameters Import
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/ai/import-patterns.txt
Use the main router export for route parameters. Avoid importing from the non-existent '/stores' path.
```javascript
import { routeParams } from '@keenmate/svelte-spa-router'
```
--------------------------------
### Get Querystring Parameters
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/CONTEXT.md
Access querystring parameters reactively using the `query` helper with TypeScript generics for type safety.
```javascript
import { query } from "@keenmate/svelte-spa-router/helpers/querystring.svelte.js";
// Define the expected type for your query parameters
interface MyQueryParams {
search?: string;
page?: number;
}
// Get reactive query parameters
const queryParams = query();
// Access parameters
$: console.log($queryParams.search, $queryParams.page);
```
--------------------------------
### Import Configuration Functions
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/CONTEXT.md
Import functions to configure routing behavior like hash mode and base path.
```javascript
import { setHashRoutingEnabled, setBasePath } from '@keenmate/svelte-spa-router/utils'
```
--------------------------------
### Custom Breadcrumb Metadata Example
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/ai/breadcrumbs.txt
Add custom properties like `icon` and `color` to breadcrumb objects for enhanced styling and functionality.
```javascript
breadcrumbs: [
{
label: 'Documents',
path: '/documents',
icon: 'folder',
color: 'blue'
},
{
label: 'Detail',
icon: 'file',
color: 'green'
}
]
```
```svelte
// In component
{#each breadcrumbs as crumb}
{crumb.label}
{/each}
```
--------------------------------
### Runtime Control of svelte-spa-router Logging
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/docs/logging.md
Demonstrates how to interact with the router's logging system at runtime via the global window API, including enabling/disabling logs, setting levels, and listing categories.
```javascript
// Check version
window.components['svelte-spa-router'].version() // "5.0.0"
// View package metadata
window.components['svelte-spa-router'].config
// { name, version, author, license, repository, homepage }
// Enable all debug logging
window.components['svelte-spa-router'].logging.enableLogging()
// Disable all logging
window.components['svelte-spa-router'].logging.disableLogging()
// Set global log level
window.components['svelte-spa-router'].logging.setLogLevel('debug')
// Enable specific category
window.components['svelte-spa-router'].logging.setCategoryLevel('ROUTER:NAVIGATION', 'debug')
// List all logging categories
window.components['svelte-spa-router'].logging.getCategories()
// ["ROUTER", "ROUTER:NAVIGATION", "ROUTER:SCROLL", ...]
```
--------------------------------
### Enable Referrer Tracking
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/ai/referrer-tracking.txt
Configure referrer tracking before mounting the application. Use 'always' for full 'Go Back' support.
```javascript
import { setIncludeReferrer } from '@keenmate/svelte-spa-router'
setIncludeReferrer('always')
```
--------------------------------
### Conditional Navigation (Svelte 4)
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/MIGRATION.md
Example of conditional navigation using Svelte 4's reactive declarations with the 'svelte-spa-router' library.
```svelte
```
--------------------------------
### Basic Route Guard Condition
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/docs/route-guards.md
Example of defining a route with an asynchronous condition that checks user authentication and admin privileges before allowing access.
```javascript
const routes = {
'/admin': wrap({
asyncComponent: () => import('./routes/Admin.svelte'),
conditions: [
// Can be sync or async
async (detail) => {
const user = await checkAuth()
return user.isAdmin
}
]
})
}
```
--------------------------------
### Nested Router Configuration
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/docs/advanced.md
Demonstrates how to set up nested routers. The parent router defines routes, and a child component (e.g., Hello.svelte) can mount another Router instance with its own routes and a prefix.
```svelte
Hello!
```
--------------------------------
### Opt-in Breadcrumb Inheritance
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/HIERARCHICAL_ROUTES_DESIGN.md
Example of implementing breadcrumb inheritance using an opt-in flag, ensuring backward compatibility and allowing gradual adoption.
```javascript
'/documents/:id/logs': createRoute({
component: DocumentLogs,
breadcrumbs: [{ label: 'Access Logs' }],
inheritBreadcrumbs: true // Opt-in, backwards compatible
})
```
--------------------------------
### Publish Package
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/DEVELOPMENT.md
Commands for packaging and publishing the npm package. Includes dry run and confirmation steps.
```bash
make check # Verify package is ready
make package # Package and validate
make publish-dry # Test publish without actually publishing
make publish # Publish to npm (requires confirmation)
```
--------------------------------
### Breadcrumb Inheritance Example
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/ai/hierarchical-routes.txt
Define routes using `createRoute` to enable breadcrumb inheritance. Child routes append their breadcrumbs to the parent's.
```javascript
import { createRoute } from '@keenmate/svelte-spa-router/wrap'
const routes = {
'/documents': createRoute({
component: Documents,
breadcrumbs: [
{ label: 'Home', path: '/' },
{ label: 'Documents' }
]
}),
'/documents/:id': createRoute({
component: DocumentDetail,
breadcrumbs: [
{ label: 'Detail' }
]
// Effective: [Home, Documents, Detail]
}),
'/documents/:id/logs': createRoute({
component: DocumentLogs,
breadcrumbs: [
{ label: 'Logs' }
]
// Effective: [Home, Documents, Detail, Logs]
})
}
```
--------------------------------
### All Available Route Metadata Helpers
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/docs/loading-metadata.md
A comprehensive list of all available helper functions for managing loading states and route metadata in Svelte SPA Router.
```javascript
import {
// Loading state control
showLoading,
hideLoading,
routeIsLoading,
// Metadata updates
updateTitle,
updateBreadcrumb,
updateRouteMetadata,
// Reactive metadata access
routeTitle,
routeBreadcrumbs,
routeContext
} from '@keenmate/svelte-spa-router/helpers/route-metadata'
```
--------------------------------
### Getting Route Pattern by Name
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/ai/named-routes.txt
Retrieve the URL pattern for a named route using `getRouteByName`. This is useful for debugging or constructing URLs manually.
```javascript
import { getRouteByName } from '@keenmate/svelte-spa-router/routes'
const pattern = getRouteByName('userProfile')
// Returns: '/user/:userId' (or undefined if not registered)
```
--------------------------------
### Navigation Functions Import
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/MIGRATION.md
Import navigation functions like push, replace, and pop from the main package or the /utils path.
```javascript
import { push } from '@keenmate/svelte-spa-router/utils'
```
--------------------------------
### Dynamic Single Segment Breadcrumbs Example
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/ai/breadcrumbs.txt
Illustrates defining breadcrumbs with a dynamic segment. The 'userName' ID is used to update the label after data is fetched.
```javascript
breadcrumbs: [
{ label: 'Home', path: '/' },
{ label: 'Users', path: '/users' },
{ id: 'userName', label: 'Loading...' }
]
```
--------------------------------
### showLoading()
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/ai/route-metadata.txt
Forces the routeIsLoading() state to true, visually indicating that content is being loaded. This can be used to trigger global overlays.
```APIDOC
## showLoading()
### Description
Force routeIsLoading() to true.
### Returns
void
```
--------------------------------
### Import Navigation Functions
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/ai/navigation.txt
Import the core navigation functions from the svelte-spa-router library.
```javascript
import { push, replace, pop, goBack } from '@keenmate/svelte-spa-router'
```
--------------------------------
### Incorrect Event Handler Naming (Svelte 4)
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/MIGRATION.md
Example of incorrect event handler prop naming using kebab-case for Svelte 4 compatibility.
```svelte
```
--------------------------------
### Query String Configuration and Reactive Accessor
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/ai/import-patterns.txt
Import functions to configure query string handling and access the reactive parsed query string.
```javascript
import {
configureQuerystring,
query // reactive parsed querystring accessor
} from '@keenmate/svelte-spa-router/helpers/querystring'
```
--------------------------------
### Import Shared Querystring Helpers
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/CONTEXT.md
Import shared reactive querystring helpers for global configuration and access.
```javascript
import { configureQuerystring, query } from '@keenmate/svelte-spa-router/helpers/querystring'
```
--------------------------------
### Define Routes with Auto-Registration
Source: https://github.com/keenmate/svelte-spa-router/blob/prod/ai/basic-setup.txt
Use defineRoutes() to auto-register route names and get type-safe navigation helpers. This is the recommended approach for enabling named routes.
```javascript
import { defineRoutes } from '@keenmate/svelte-spa-router/routes'
const { routes, nav, paths } = defineRoutes({
home: { path: '/', component: Home },
userProfile: { path: '/user/:userId', component: UserProfile }
})
export { routes, nav, paths }
```
```javascript
import { routes } from './routes'
// no separate registerRoutes() call needed
// Now you can navigate by name:
await push('userProfile', { userId: 123 }) // → /user/123
// Or with the typed helper:
nav.userProfile.push({ userId: 123 })
```