A simple svelte router based on location API
npm install sly-svelte-location-routerA lightweight and flexible router for Svelte applications with advanced nested routing capabilities, leveraging path-to-regexp for powerful route matching.
- Nested Routing: Full support for deeply nested router hierarchies
- Context-based Route Resolution: Efficient segment-by-segment route resolution
- Fallback Propagation: Error handling that bubbles up through router hierarchy
- Route Redirects: Simple string-based route redirection
- Path Parameters: Dynamic route parameters with full TypeScript support
- Lazy Loading: Automatic code-splitting with dynamic imports
- Auto-initialization: Routers initialize automatically when mounted
- TypeScript First: Complete TypeScript support with strict typing
- Longest Path Matching: Intelligent route sorting prioritizes longer, more specific paths
``bash`
pnpm install sly-svelte-location-router
`svelte
Loading...
`
For advanced use cases where you need precise control over router initialization, you can use initRouter() instead of the Router component:
`svelte
Nested Routing
Create complex nested route structures by using Router components within your route components:
`svelte
import('./admin/NotFound.svelte')}>
Loading admin content...
`URL Examples:
-
/admin → Admin layout + Dashboard
- /admin/users → Admin layout + Users list
- /admin/users/123 → Admin layout + User detail for ID 123
- /admin/invalid → Admin layout + Admin-specific 404 pageRoute Resolution Strategy
The router uses a sophisticated segment-by-segment resolution strategy:
1. Longest Path First: Routes are sorted by length and specificity
2. Segment Consumption: Each router consumes matching path segments
3. Remaining Propagation: Unmatched segments pass to nested routers
4. Fallback Bubbling: Unresolved routes trigger fallbacks up the hierarchy
Example with
/shop/products/123:
`
Main Router: matches '/shop' → loads Shop component, remaining: ['products', '123']
Shop Router: matches '/products/:id' → loads ProductDetail, remaining: []
`Route Definitions
$3
`typescript
'/users/:id': () => import('./routes/UserDetail.svelte')
`$3
`typescript
'/posts/:category/:id': {
name: 'post-detail',
component: () => import('./routes/PostDetail.svelte')
}
`$3
`typescript
'/old-users': '/users', // Simple redirect
'/legacy/:id': '/users/:id' // Parameter-preserving redirect
`$3
Protect routes with async guard functions:
`typescript
'/admin': {
name: 'admin',
component: () => import('./routes/Admin.svelte'),
guard: async () => {
const isAuthenticated = await checkAuth();
if (!isAuthenticated) {
// Redirect with state
return {
path: '/login',
state: { message: 'Please login to access admin area' }
};
}
return null; // Allow access
}
}
`Route Props
All route components receive a standardized
route prop containing route information. The examples use Svelte 5's rune syntax ($props(), $derived) for modern, reactive component development:`typescript
interface RouteProps {
params?: RouteParams // Route parameters from URL
error?: ErroneousRouteStore // Error info for fallback components
state?: any // Navigation state data
search?: { [key: string]: string } // Query parameters from URL search string (only for final route)
}
`$3
`svelte
User: {userId}
`Supported Parameter Types:
-
:id - Required parameter
- :id? - Optional parameter
- :path* - Zero or more segments
- :path+ - One or more segments$3
Access state passed during navigation or from guards:
`svelte
{#if message}
{message}
{/if}
`$3
Access URL query parameters in the final route component:
`svelte
Products
{#if category}
Filtered by: {category}
{/if}
`Note: Query parameters are only available in the final route component, not in intermediate nested routers.
$3
Fallback components receive error information through the same interface:
`svelte
404 - Not Found
The path "{errorPath}" could not be found.
`Programmatic Navigation
`typescript
import { navigate } from 'sly-svelte-location-router';// Navigate to a new route
navigate('/users/123');
// Navigate with state
navigate('/dashboard', { from: 'login', userId: 123 });
// Works with nested routes
navigate('/admin/users/456');
`Error Handling & Fallbacks
Fallbacks handle unmatched routes and can be defined at any router level:
`svelte
import('./routes/404.svelte')}>
Loading...
import('./admin/NotFound.svelte')}>
Loading admin...
`Fallback Resolution:
1. Child router tries to match route
2. If no match, checks for local fallback
3. If no local fallback, error propagates to parent
4. Parent router tries its fallback
5. Process continues up the hierarchy
Advanced Examples
$3
`
/ → Homepage
/products → Product list
/products/123 → Product detail
/cart → Shopping cart
/admin → Admin dashboard
/admin/products → Admin product management
/admin/orders → Admin order management
`$3
`svelte
import('./routes/404.svelte')}>
Loading...
`TypeScript Support
Full TypeScript support with strict typing:
`typescript
import type { Routes, RouteProps, RouteDefinition } from 'sly-svelte-location-router';const routes: Routes = {
'/users/:id': () => import('./UserDetail.svelte')
};
// In your component (Svelte 5)
let { route }: { route: RouteProps } = $props();
// Type-safe access to params
const userId = $derived(route.params?.id);
`API Reference
$3
- routes: Routes - Route configuration object
- fallback?: RouteDefinition - Fallback component for unmatched routes
- children? - Loading component (rendered during route transitions)$3
Programmatic navigation function with optional state.$3
Manual router initialization function. Use this instead of the Router component when you need to implement custom route resolution logic. This function sets up URL change listening and navigation event handling, but you'll need to implement your own route matching and component rendering.$3
Svelte store containing the current route information. Contains path, params, and parentPath for reactive route tracking.$3
- Routes - Route configuration object type
- RouteDefinition - Union type for route definitions
- RouteProps - Props interface for route components
- RouteParams - Route parameter object type
- RouteComponent - Lazy-loaded component type
- RouteGuard` - Guard function type for route protectionMIT
Contributions welcome! Please feel free to submit a Pull Request.